Scanner input skipping next input - java

I am now having a difficult time fixing this problem.
So, I have this code snippet here which asks 3 input from the user.
case 0:
String accnum,pin,name;
System.out.print("Enter account name: ");
name = input.nextLine();
System.out.print("Enter account number: ");
accnum = input.next();
System.out.print("Enter account PIN: ");
pin = input.next();
atm.set_accinfos(name,accnum,pin);
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
break;
But everytime I run it, it always skips the input for the String "name", I tried using input.next(); on it and it works but then it will now skip the input for String "accnum".
EDIT: It also just happens if the input from "name" has a space on it, for example : John Doe.
Am I missing something here?

The nextLine() gobbles the newline character produced by the next() of account pin (when you hit enter). So, it won't ask for name. Add input.nextLine() after pin = input.next(); and try

Try This. i think problem with next(). since next reads input as tokens with default delimiter(i think space is the default delimiter).:
case 0:
String accnum,pin,name;
System.out.print("Enter account name: ");
name = input.nextLine();
System.out.print("Enter account number: ");
accnum = input.nextLine();
System.out.print("Enter account PIN: ");
pin = input.nextLine();
atm.set_accinfos(name,accnum,pin);
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
break;

If you're using input anywhere before this block of code, then you need to be sure to call nextLine earlier on.
If you use next instead, then your input stream will still contain a new line character (\n). Thus, when you start this block of code with nextLine, that call will take the previous \n and not the name which was just entered.
In general, if your Scanner is reading System.in, then you should use nextLine everywhere. next, nextInt, and the other next methods are meant for more predictable data.

Okay, thats for the help everyone, I managed to fix it by adding "input.nextLine();" before "name = input.nextLine();"

Related

Java program not able to exectue nextLine() properly

When I run my program instead of reading the string and storing it in tempAddress my program simply prints the next line before I enter input. Using next works for the first two because I am only using one word but the third one encompasses multiple words so need something else and through my research I found nextLine() was the answer but I am not able to get it to work as others have, thanks in advance.
System.out.println("Enter Employee First Name: ");
String tempFirstName = input.next();
employeesArray[i].setFirstName(tempFirstName);
System.out.println("Enter Employee Last Name: ");
String tempLastName = input.next();
employeesArray[i].setLastName(tempLastName);
System.out.println("Enter Employee Address: ");
String tempAddress = input.nextLine();
employeesArray[i].setAddress(tempAddress);
System.out.println("Enter Employee Title: ");
String tempTitle = input.next();
employeesArray[i].setTitle(tempTitle);
Basically Scanner tokenizes the input by default using whitespace. Using next() method of scanner returns the first token before the space and the pointer stays there. Using nextLine() returns the whole line and then moves the pointer to the next line.
The reason your nextLine() was not behaving fine was because, your previous input for employee last name using next() cause the pointer to stay in the line hence, when you reach the point to take the employee address using nextLine(), the pointer returns remainder of the previous input next() which was obviously empty (when supplied one word as input to next()). Assume you entered two words separated by space for last name, the next() will store the first word in last name field and pointer waits after first token before second token and as soon as you reach nextLine() pointer returns the second token and moves to new line.
The solution is to execute nextLine() after reading the input for last name to make sure that your pointer is in new line waiting for input for address.
I updated my code by inserting a input.nextLine() there to make sure that scanner input is consumed and pointer is moved to the next line.
System.out.println("Enter Employee First Name: ");
String tempFirstName = input.next();
employeesArray[i].setFirstName(tempFirstName);
System.out.println("Enter Employee Last Name: ");
String tempLastName = input.next();
employeesArray[i].setLastName(tempLastName);
//feed this to move the scanner to next line
input.nextLine();
System.out.println("Enter Employee Address: ");
String tempAddress = input.nextLine();
employeesArray[i].setAddress(tempAddress);
System.out.println("Enter Employee Title: ");
String tempTitle = input.next();
employeesArray[i].setTitle(tempTitle);
When you have input.next(), it reads the input, but not the newline character, it leaves it in the input stream. input.nextLine() ends with a newline character. So when input.nextLine() is executed, it stops without taking any input because it already got the newline (\n) char from the input stream.
Solution: read the newline before you execute inupt.nextLine():
System.out.println("Enter Employee Address: ");
input.next();//read the newline char - and don't store it, we don't need it.
String tempAddress = input.nextLine();
see also: https://stackoverflow.com/a/13102066/3013996

scanner nextLine() allowing input that is either one or two words

I know this has been asked to death, but I have yet to search and find a case quite like mine so i figured i'd ask...I have this little code here...
System.out.print("What would you like the name of your new recipe to be? ");
Recipe tempRecipe = new Recipe(name);
name = scan.nextLine();
scan.nextLine();
tempRecipe.setName(name);
System.out.print("How many ingredients does this recipe have? ");
ingredientCount = scan.nextInt();
scan.nextLine();
Now obviously I was running into the issue where the println statements were on the same line and not allowing input, so i threw in that scan.nextLine() to solve the problem. But now the issue is when i read something in it just gives me blank because of too much nextLine()! if I change it to name = scan.next() i can only read in one word and i need to be able to read in both 1 or 2 words indiscriminately if need be, it might also help to know that following this code are these lines
Ingredient tempIngredient = new Ingredient(name, quantity, null);
System.out.print("Enter the name of ingredient number " + (i+1) + ": ");
name = scan.nextLine();
tempIngredient.setName(name);
System.out.print("Enter the quantity of ingredient number " + (i+1) + ": ");
quantity = scan.nextDouble();
scan.nextLine();
tempIngredient.setQuantity(quantity);
System.out.print("Enter the unit of measurement of ingredient number " + (i+1) + ": ");
unit = scan.nextLine();
tempIngredient.setUnit(UnitOfMeasurement.valueOf(unit));
Both tempRecipes name and tempIngredients name need to be capable of holding 1 or 2 words if need be, how do i do this while still fixing the nextLine() problem!?
Call the extra scan.nextLine() only after scan.nextInt(), and not after scan.nextLine(). The idea of using the extra scan.nextLine() is to skip to new-line character and go to the next line (since scan.nextInt() does not do that).
See Scanner issue when using nextLine after nextXXX

Issues with nextLine(); [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Scanner issue when using nextLine after nextInt
I am trying create a program where it lets the user inputs values into an array using scanner.
However, when the program asks for the student's next of kin, it doesn't let the user to input anything and straight away ends the program.
Below is the code that I have done:
if(index!=-1)
{
Function.print("Enter full name: ");
stdName = input.nextLine();
Function.print("Enter student no.: ");
stdNo = input.nextLine();
Function.print("Enter age: ");
stdAge = input.nextInt();
Function.print("Enter next of kin: ");
stdKin = input.nextLine();
Student newStd = new Student(stdName, stdNo, stdAge, stdKin);
stdDetails[index] = newStd;
}
I have tried using next(); but it will only just take the first word of the user input which is not what I wanted. Is there anyway to solve this problem?
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();.
// rest of the code
The problem is with the input.nextInt() this function only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine().
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();
Function.print("Enter next of kin: ");
stdKin = input.nextLine();
Why next() is not working..?
next() returns next token , and nextLine() returns NextLine. It good if we know difference. A token is a string of non blank characters surrounded by white spaces.
From Doc
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Make input.nextLine(); call after input.nextInt(); which reads till end of line.
Example:
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine(); //Call nextLine
Function.print("Enter next of kin: ");
stdKin = input.nextLine();

Scanning a String with a comma

I have created a Scanner with system.in.
How do I allow an input to be able to have commas in it without going to the next input?
For example:
System.out.print("Enter City, State.");
String location = scan.nextLine();
I cannot enter city,state because the language thinks I want to proceed to the next scanning input question. How do I allow commas in a scanning string?
*Whole Code
Scanner scan1 = new Scanner (System.in);
System.out.print ("City, State: ");
String location1 = scan.nextLine();
System.out.print ("Enter number: ");
number1 = scan.nextDouble();
System.out.print ("Enter number: ");
number2 = scan.nextDouble();
System.out.print ("City, State: ");
String name2 = scan1.nextLine();
System.out.print ("Enter #: ");
number3 = scan.nextDouble();
System.out.print ("Enter #: ");
number4 = scan.nextDouble();
scan.nextLine(); will return the entire line, commas or not.
If that isn't what's happening, then the problem must be elsewhere and you should provide more code.
Re: full code: That still works. What is the error you're getting / unwanted behavior?
What I think is happening is that the nextLine() is catching the end-of-line character from your previous input.
What happens:
Suppose you enter a number like 12.5 and press enter.
The buffer that Scanner reads from now contains 12.5\n where \n is the newline character.
Scanner.nextDouble only reads in 12.5 and \n is left in the buffer.
Scanner.nextLine reads the rest of the line, which is just \n and returns an empty string. That's why it skips to the next input: it already read "a line".
What I'd do to fix it:
System.out.print ("City, State: ");
String name2;
do{
name2 = scan1.nextLine();
}while( name2.trim().isEmpty() );
What this loop does is it keeps reading the next line until there is a line with something other than whitespace in it.
One possible solution: get the next line as you're doing and then use String#split on it to split on the comma (either that or use a second Scanner object that takes that String as input). If there is only one comma, then splitting on "," will give you an array that holds two Strings. You'll need to trim the second String to get rid of whitespace, either that or split on a more fancy regular expression.
You can either use split as mentioned above, or you could create another scanner on the next line, this would especially be useful if you have more than one fields separated by a ",".
System.out.print ("City, State: ");
Scanner temp = new Scanner(scan.nextLine());
temp.useDelimiter(",");
while(temp.hasNext()){
//use temp.next();
//Do whatever you want with the comma separated values here
}
But I still suggest that if you are just looking at something as simple as "City,State" , go for split.

System.out.print is overlapping the questions why?

My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:
"Enter the second student's name: Enter the student's score: "
instead of
"Enter the second students's name: "
"Enter the student's score: "
I also can not input data into the System.out.print method of the second student
My main code where the error is:
System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
System.out.print("Enter the students's score: ");
score = reader.nextInt();
student1.setScore(i, score);
}
System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
System.out.print("Enter the students's score: "); //program skips to here to input
//data
score = reader.nextInt();
student2.setScore(i, score);
}
the part that deals with the error from the class is as follows
public void setName(String nm){
name = nm;
}
You should call println() to print a newline character, after reading the input.
If by "overlapping" you mean they appear on the same line then you want System.out.println, rather than System.out.print. println emits a trailing newline.
Could you more clearly describe this 'overlapping'? In your original question your 'one versus the other' were identical. Make it a code sample if need be to preserve spacing and such,
I believe you are talking about how all the lines are printed on the same line. You need to either use line break characters '\n' in Java, or use System.out.println
Try inserting:
reader.nextLine();
...before
System.out.print("Enter the second student's name: ");
.nextInt() doesn't swallow the newline from your input, so the next call to nextLine() just gets the newline character and returns you an empty string - and the program continues, printing the next line of output.
If what I understand is right, you may probaly have problems with the input of the java console. I can't tell much because there's not enough information, but maybe you can refer this link for getting input in java console: http://www.abbeyworkshop.com/howto/java/readLine/index.html
And I recommend clearing the un-affected code (about class Student), just check the input & output from console only.

Categories

Resources