user input string and integers in Java [duplicate] - java

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
System.out.print("Name : ");
String name = in.nextLine();
System.out.print("Age : ");
int age = in.nextInt();
System.out.print("City : ");
String city = in.nextLine();
the output will be :
Name : test
Age : 20
BUILD SUCCESSFUL
when i debug them, it won't read the user input for "city" . but when i changed the data type for "age" to string, it will read. how can i kept the data type of age to int with the system reading the user inputs for city ?

As there is still a new line character in the buffer after reading the age, change it to..
System.out.print("Name : ");
String name = in.nextLine();
System.out.print("Age : ");
int age = in.nextInt();
//add
in.nextLine();
System.out.print("City : ");
String city = in.nextLine();

Try this,
System.out.print("Age : ");
int age = Integer.parseInt(in.nextLine());

There is still a new line character in the buffer after reading the age. Try adding a in.nextLine before you ask for the city value.

Related

Scanner is skipping one line and going to the next [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Difference between next() and hasNext() in java collections
(5 answers)
Closed 1 year ago.
I am trying to input some text using a scanner but I am having an issue where the output for name is skipping and going to the next line. If I try to input name it will skip and go straight to surname. Can anyone please assist
Scanner input = new Scanner(System.in);
if(input.hasNext("1")){
System.out.print("Input your Name: ");
name = input.next();
System.out.print("Input your Surname: ");
surname = input.next();
System.out.print("Input your ID: ");
id = input.nextInt();
System.out.print("Input the training program: ");
trainingProgramme = input.next();
registerApplicant(name, surname, id, trainingProgramme);
System.out.print("Congratulations! You have registered for the " +trainingProgramme+ " Training Programme");
}
The output:
debug:
Welcome to the Codex Registration system:
Please select an option:
1 Register for a training program
2 Check registration details
3 Exit program
1
Input your Name: Input your Surname: Blah
Input your ID: 6787
Input the training program: Java
Congratulations! You have registered for the Java Training ProgrammeWelcome to the Codex Registration system:
Please select an option:
The problem is, that with input.hasNext("1") you are not skipping the input 1 from the user.
So the input 1 will be stored to your variable name.
Therefore you need to skip this input. One possibility is to put a input.next() before reading the name like this:
Scanner input = new Scanner(System.in);
if(input.hasNext("1")){
input.next(); //skip the input of choice
System.out.print("Input your Name: ");
name = input.next();
System.out.print("Input your Surname: ");
surname = input.next();
System.out.print("Input your ID: ");
id = input.nextInt();
System.out.print("Input the training program: ");
trainingProgramme = input.next();
registerApplicant(name, surname, id, trainingProgramme);
System.out.print("Congratulations! You have registered for the " +trainingProgramme+ " Training Programme");
}
or (imho the better way) you use a variable for the choice-input:
Scanner input = new Scanner(System.in);
String selection = input.next();
if("1".equals(selection)){
//...
}
The problem is that a new line character added to end of the every scanner-
You can manually set the delimiter of the Scanner:
scanner = new Scanner(...).useDelimiter(" "); //To use only space as a delimiter.
Try to use a new variable for choice.
Scanner input = new Scanner(System.in);
String choice = input.next();
if (choice =="1") {
System.out.print("Input your Name: ");
name = input.next();
System.out.print("Input your Surname: ");
surname = input.next();
System.out.print("Input your ID: ");
id = input.nextInt();
System.out.print("Input the training program: ");
trainingProgramme = input.next();
registerApplicant(name, surname, id, trainingProgramme);
System.out.print("Congratulations! You have registered for the " +trainingProgramme+ " Training Programme");
}

Splitting a Scanner Input Into Strings

I've been looking for an answer to this for a while, but for some reason, none of them seem to work.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter full name (last, first)");
String[] personalInfo = scanner.next().split(", ");
String firstName = personalInfo[1];
String lastName = personalInfo[0];
System.out.println("Your info: " + firstName + " " + lastName);
There is my code. I'm basically trying to obtain the personal info, which would be the first and last name. I want to split the first and last name into 2 different strings, but whenever I try to print this, I get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 > out of bounds for length 1
at Fines.main(Fines.java:11)
I'm confused because I even started the array with 0 like I was supposed to.. I just don't understand what is going incorrectly.
Please give me a hand - thanks in advance!
What you want is scanner.nextLine() to read from standard input up until end of line. Then split would work as you expected.
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter full name (last, first)");
String[] personalInfo = scanner.nextLine().split(", ");
String firstName = personalInfo[1];
String lastName = personalInfo[0];
System.out.println("Your info: " + firstName + " " + lastName);
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 1 > out of bounds for length 1 at Fines.main(Fines.java:11)
As the size of the personalInfo is 1 not 2.
use nextLine() instead of next() because next() will only return the input that comes before a space.
String[] personalInfo = scanner.next().split(", "); should be
String[] personalInfo = scanner.nextLine().split(", ");
You might want to read this What's the difference between next() and nextLine() methods from Scanner class?
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Please enter full name (last, first)");
String firstName = scan.next();
String lastName = scan.next();
System.out.println("Your info: " + firstName + ' ' + lastName);
}
scanner.next() read until next delimiter (space by default), so it ready only the firstName. Just replace it with scanner.nextLine() or use scanner.next() two times.

Limiting the number of characters in a user Scanner input in String in Java

This code is supposed to print the user's name when they enter it and limit it's length to 20 characters, but it only works when the user's name is longer than 20 chars. I get en error when it's below 20. Any ideas on how to fix this?
Thank you.
String name;
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
String cutName = name.substring(0, 20);
if (name.length()>20) {
name = cutName;
System.out.print("Hello " +name+"!");
}
Just take the lower index between 20 and the String 's length .
name.substring(0, Math.min(20,name.length()));
If you place your String cutName inside the if, the error should disappear. You cannot take a substring from a string that is longer than the String itself.
if (name.length()>20) {
String cutName = name.substring(0, 20);
name = cutName;
}
System.out.print("Hello " +name+"!");
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
if(name.length()>20)
name = name.substring(0,20);

Make an email list, by entering only recipient names

I want to make a simple code, that prompts you to enter names, separated by comma or just a space, and when you click enter, to take every one word you entered, and put a #gmail.com at the end of it, how can I do it?
That's what I have for now
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
String names;
System.out.println("Enter names: ");
names = input.next();
System.out.println(names + mail);
This should be everything you asked for, if you put a list of names separated by commas it will loop through them, otherwise it will just print a single name.
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
System.out.println("Enter names: ");
String names = input.next();
if(names.contains(",")) {
for(String name : names.split(",")) {
System.out.println(name + mail);
}
} else {
System.out.println(names + mail);
}
Hope that helps.
Not knowing what language this is, here's the pseudo-code:
names = input.next();
namesArray = names.split(" ") -- replace with your preferred delimiter
foreach name in namesArray
print name + mail

How to read Strings with spaces inside while loop (Java)

This always gives me a headache. I am trying to read and save multiple-word Strings for the fields "name" and "malady" within a while loop. Here is my code:
while(OR1.isFull() == false || OR2.isFull() == false)
{
// prompt for next request
System.out.println("Enter patient info:");
// read patient info
System.out.print("Name: ");
String name = input.nextLine();
input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
// store patient info
Patient patient = new Patient(name, malady, priority);
OR1.add(patient);
} // end while
System.out.println("List of patients scheduled for Operating Room 1");
while(OR1.isEmpty() == false)
{
// pop and print root
System.out.print(OR1.remove());
}
And here is what my console input and output looks like:
Enter patient info:
Name: John Doe
Malady: Broken hip
Priority: 6
List of patients scheduled for Operating Room 1
Patient: Malady: Broken hip Priority: 6
// end console output.
Notice that it did not record the value I entered for "Name," and also that it prompted for an extra line of input after obtaining "Malady" (required me to press enter again to get it to ask for the next input, "Priority").
I have read the documentation at http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html. I have tried different combinations of next() and nextLine(). I just don't get it.
Problem solved by changing the code to the following:
// read patient info
System.out.print("Name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
Though I am still confused about how this silly scanner works =/
I believe it should work for just:
// read patient info
System.out.println("Name: ");
String name = input.nextLine();
System.out.println("Malady: ");
String malady = input.nextLine();
System.out.println("Priority: ");
int priority = input.nextInt();
Perhaps the problem is in the Patient constructor or something?
Problem solved by changing the code to the following:
// read patient info
System.out.print("Name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();

Categories