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);
Related
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
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 6 years ago.
Is it able for the code bellow to run correctly without creating a new Scanner object inside the loop?
Can it be done with just a definition of a Scanner object outside the loop(commented code)?
// Scanner sc = new Scanner(System.in);
while(true){
Scanner sc = new Scanner(System.in);
try{
int x = sc.nextInt();
System.out.printf("You gave %d\n", x);
}catch(Exception e){
System.out.println("Plz give a valid number!");
}finally{
sc.close();
}
}
When you define the Scanner outside of the loop, you are using the same scanner on each run of the loop. If the next token is not a valid integer, sc.nextInt() will fail and the scanner will not advance beyond that token. On the next iteration, sc.nextInt() will see the same invalid token and will fail again. Similarly, if you close the scanner, the next iteration of the loop will call sc.nextInt() on the closed scanner, which will fail. Subsequent iterations will fail for the same reason.
On the other hand, when the scanner is defined within the loop, each iteration uses a new scanner. Even if sc.nextInt() fails, the next iteration will use a fresh scanner that doesn't contain the same invalid token.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I know a lot of people have asked this but everyones answer is to use scanner.nextLine() however this does not work for me. I have this code:
if (option == 1) {
System.out.println("What is the name of the goal the task is under?: ");
String goalName = scanner.next();
}
When I use .next() I can only get one word, however when I use .nextLine() the command line does not allow for the user to input anything so it asks "What is the name of the goal the task is under?:" and then continues on the program without letting input occur.
The following test code works:
package asdfsadf;
import java.util.Scanner;
public class Asdfsadf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("What is the name of the goal the task is under?: ");
String goalName = scanner.nextLine();
System.out.println("You entered: ");
System.out.print(goalName);
}
}
So the only problem would be if you used scanner before this say you had scanner.nextInt() and that would leave an empty "end of the line" in the scanner. So the nextLine would take the end of the line from the previous call. To fix this, just create a new scanner object.
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()?
(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