This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I get an error when i try to input name and num in a loop,
int i = 1;
while(i <3) {
System.out.print("Please enter name: ");
String name = input.nextLine();
System.out.print("Please enter number: ");
int num = input.nextInt();
i++;
}
The error that i am getting is this
on the first iteration the input is normal, however on the second iteration it prints the enter num and name at the same line. Could anyone explain to me why is this happening?
when calling nextInt() you only read the integer, but there is a new line character that should also be read.
so at the end of the loop, call input.nextLine() to read the new line.. and then the rest of the loop should work fine.
https://stackoverflow.com/a/26626204/14951486
Already answered
Refer the link
Error because you are taking String input after int
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I am writing a code that asks for user input on the names of the players and stores them in array. To do this I am using a for loop, which i thought would be more efficient, however, the code seems to do something unexpected, and I cannot see why it is doing what it does. Below is the code and the result:
Scanner reader = new Scanner (System.in);
System.out.print("Please enter the number of players:");
int players = reader.nextInt();
String[] player_name = new String[players+1];//Array to store player names
for (int i = 0; i < players; i++)//Loop to ask players their name
{
System.out.print("Player " + (i+1) + " please enter your name:\n");//Asks player names one by one
player_name[i] = reader.nextLine();//Saves the player names to the array
}
And here is the result when the number of players is 2:
Please enter the number of players:2
Player 1 please enter your name:
Player 2 please enter your name:
wa
BUILD SUCCESSFUL (total time: 23 seconds)
When I hit enter after typing the "name" wa to type player 2's name the program just ends.
The nextInt() doesn't grab the end of line character, AKA the "enter" after the number is entered. Instead you can use nextLine() and get the entire line and then parse it into an Integer like so
int players = Integer.parseInt(reader.nextLine());
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();
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()
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 8 years ago.
Consider the following snippet:
System.out.print("input iteration cycles");
Scanner reader=new Scanner(System.in);
int iteration = reader.nextInt();
System.out.print("input choice: Var or par");
String choice=reader.nextLine();
System.out.print(choice);
I was hoping to get one line where it prints the first input and the next print out to only print the next input which is either var or par, however it seems that the second print prints out the second input in addition to the first input. Any idea why?
nextInt() does not advance to the next line. So you must make an explicit call to nextLine() immediately after it. Otherwise, choice will be given that newline. Just add this line to your code:
System.out.print("input iteration cycles");
Scanner reader=new Scanner(System.in);
int iteration = reader.nextInt();
reader.nextLine(); //<==ADD
System.out.print("input choice: Var or par");
String choice=reader.nextLine();
System.out.print(choice);
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I was writing my first, well second if you count hello world, program and ran into a small issue.
My code:
import java.util.*;
class test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What is your name: ");
String name = scan.nextLine();
System.out.print("What is your favorite number: ");
int favoriteNumber = scan.nextInt();
System.out.print("What is your favorite game: ");
String game = scan.nextLine();
}
}
So it scans in name and favoriteNumber but the program ends before asking the user to enter a favorite game. Essentially the user can only enter text twice instead of three times like I would like.
Just a guess: scan.nextInt() does not consume the trailing newline character after the user presses enter. The subsequent call to scan.nextLine() then finds a newline character waiting.
Try switching out int favoriteNumber = scan.nextInt(); for String favoriteNumber = scan.nextLine(); to see if that fixes the issue. If it does, my hypothesis is correct.
If that is the case, then you should probably use Integer.parseInt to convert this string into an integer. The problem here is effectively that you really want to collect 3 lines of input, where a line is defined as "any sequence of characters ending with a newline". Your program is currently written to request a line, an int, then a line, rather than "3 lines of input, one of which contains an int".
an exception must be thrown in here scan.nextInt();
Check whether you entered a proper int