This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 28 days ago.
So I instantiate the Scanner scan a lot earlier but it skips right over my second scan.nextLine() after scan.nextInt(). I don't understand why it skips over it?
System.out.println("Something: ");
String name = scan.nextLine();
System.out.println("Something?: ");
int number = scan.nextInt();
System.out.println("Something?: ");
String insurer = scan.nextLine();
System.out.println("Something?: ");
String another = scan.nextLine();
because when you enter a number
int number = scan.nextInt();
you enter some number and hit enter, it only accepts number and keeps new line character in buffer
so nextLine() will just see the terminator character and it will assume that it is blank String as input, to fix it add one scan.nextLine() after you process int
for example:
System.out.println("Something?: ");
int number = scan.nextInt();
scan.nextLine(); // <--
When you call int number = scan.nextInt(); it does not consume the carriage return that has been pushed, so this is does at the next scan.nextLine();
You want your code to be
....
System.out.println("Something?: ");
int number = scan.nextInt();
scan.nextLine(); // add this
System.out.println("Something?: ");
String insurer = scan.nextLine();
The method nextInt() will not consume the new line character \n. This means the new line character which was
already there in the buffer before the nextInt() will be ignored.
Next when you call nextLine() after the nextInt(), the nextLine() will consume the old new line
character left behind and consider the end, skipping the rest.
Solution
int number = scan.nextInt();
// Adding nextLine just to discard the old \n character
scan.nextLine();
System.out.println("Something?: ");
String insurer = scan.nextLine();
OR
//Parse the string to interger explicitly
String name = scan.nextLine();
System.out.println("Something?: ");
String IntString = scanner.nextLine();
int number = Integer.valueOf(IntString);
System.out.println("Something?: ");
String insurer = scanner.nextLine();
All answers given before are more or less correct.
Here is a compact version:
What you want to do: First use nextInt(), then use nextLine()
What is happening: While nextInt() is waiting for your input, you press ENTER key after you type your integer. The problem is nextInt() recognizes and reads only numbers so the \n for the ENTER key is left behind on the console.
When the nextLine() comes again, you expect it to wait till it finds \n. But what do you didn't see is that \n is already lying on the console because of erratic behavior of nextInt() [This problem still exists as a part of jdk8u77].
So, the nextLine reads a blank input and moves ahead.
Solution: Always add a scannerObj.nextLine() after each use of scannerObj.nextInt()
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
Why when the first time process go into the loop, it doesn't stop and wait for user input string first, instead will print out the space and enter? It will only stop on the second time of loop and wait for the user to input something.
It's hacker rank 30 Days of code > Day 6 problem by the way.
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner stdin = new Scanner(System.in);
int input;
input = stdin.nextInt();
while( input-- >= 0 ){
String sentence = stdin.nextLine();
char[] CharArray = sentence.toCharArray();
for( int i=0; i < sentence.length() ; i=i+2 ){
System.out.print(CharArray[i]);
}
System.out.print(" ");
for( int i=1; i < sentence.length() ; i=i+2 ){
System.out.print(CharArray[i]);
}
System.out.println();
}
stdin.close();
}
When you enter a number, you also press the ENTER key to enter your input. So the following line consumes the number, but it does not consume the carriage return:
input = stdin.nextInt();
Instead, that carriage return is consumed in the first iteration of the loop by this line:
String sentence = stdin.nextLine();
In other words, it appears from your point of view that the first iteration of the loop did not prompt you for any input, because you unknowingly already entered it. If you want to avoid this, you can add an explicit call to Scanner.nextLine():
input = stdin.nextInt();
stdin.nextLine();
When you enter a number and press enter, nextInt() reads the integer you entered but the '\n' character is still in the buffer, so you need to empty it before entering the loop, so you can simply write : stdin.nextLine() before entering the loop
On first time, you are scanning twice.
input = stdin.nextInt();
it will wait for your input.once you give value it will move ahead. then again
String sentence = stdin.nextLine();
it will take enter(or carriage return) and print that with space.
after this it will work properly
Solution :
use stdin.nextLine(); just after input = stdin.nextInt();
You need to add one more -
stdin.nextLine();
after
input = stdin.nextInt();
without collecting it in some variable. This will consume the newline character appeared just after you finished inputting your integer in below line -
input = stdin.nextInt();
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
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Just one question: why I must type answer = in.nextLine(); twice? If this line is single the program doesn't work as expected. Without second line the program doesn't ask you to enter a string.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String answer = "Yes";
while (answer.equals("Yes")) {
System.out.println("Enter name and rating:");
String name = in.nextLine();
int rating = 0;
if (in.hasNextInt()) {
rating = in.nextInt();
} else {
System.out.println("Error. Exit.");
return;
}
System.out.println("Name: " + name);
System.out.println("Rating: " + rating);
ECTS ects = new ECTS();
rating = ects.checkRating(rating);
System.out.println("Enter \"Yes\" to continue: ");
answer = in.nextLine();
answer = in.nextLine();
}
System.out.println("Bye!");
in.close();
}
}
The Scanner-Object has an internal cache.
You start the scann for nextInt().
You press the key 1
You press the key 2
You press return
Now, the internal Cache has 3 characters and the scanner sees the third character(return) is not a number, so the nextInt() will only return the integer from the 1st and 2nd character (1,2=12).
nextInt() returns 12.
Unfortunately the return is still part of the Scanner's cache.
You call nextLine(), but the Method scans its cache for a newline-marker that has been kept in the cache from before the nextInt() call returned.
The nextLine() returns a 0-length-string.
The next nextLine() has an empty cache! It will wait until the cache has been filled with the next newline-marker.
reset()
There is a more elegant way to clear the cache instead of using nextLine():
in.reset();
Because you are using nextInt() this method only grabs the next int it doesn't consume the \n character so the next time you do nextLine() it finishes consuming that line then moves to the next line.
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();
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.