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.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm new to java and I wrote this code
import java.util.Scanner;
public class GamingJava {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String Name;
int password;
String yEs;
System.out.print("hello sir what is your name? ");
Name = input.nextLine();
System.out.print("what is your password? ");
password = input.nextInt();
System.out.println("your name was "+Name+" and your password was "+password);
System.out.print("are you sure? ");
yEs = input.nextLine();
System.out.println(yEs);
}
}
It only ask the name and the password, but Java doesn't ask the last one how did that happen?
It asks for the input and immediately takes it as an empty string i.e. "".
Root Cause : The issue is because of the nextLine() method. Since while providing an input, user has to press the Enter key, the cursor/prompt on the console moves to next line. This line is taken as an empty line by the nextLine() method.
Solution : You must use the next() method as it looks out for the presence of space character for taking the input.
FYR the following line of code
yEs = input.nextLine();
should be changed to
yEs = input.next();
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am a beginner programmer student from Finland, this is my first post here so hello everyone! So, I am writing this Java program that reads user inputs and creates new Books according to the inputs and then adds them to list and sorts them according to their recommended ages and names. The following code doesn's seem to work, the loop breaks automatically after one go. I actually fixed the issue using "Integer.valueOf" instead of nextInt but I started wondering why the nextInt doesn't work here?
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Book> books = new ArrayList<>();
while (true) {
System.out.println("Enter books name, blank will end the loop:");
String bookName = reader.nextLine();
if (bookName.equals("")) {
break;
}
System.out.println("Enter the books recommended age:");
int minimAge = reader.nextInt();
Book book = new Book(bookName, minimAge);
books.add(book);
}
System.out.println("Total " + books.size() + " books.");
System.out.println();
System.out.println("Books:");
Comparator<Book> vertaus = Comparator
.comparing(Book::getMinimAge)
.thenComparing(Book::getName);
Collections.sort(books, vertaus);
for (Book k : books) {
System.out.println(k);
}
}
}
While entering number for minimAge when you press enter, the scanner takes two input, the number and a EOF character. As a result EOF character is set as the next bookname. Which is equivalent to empty string and breaks the loop. To skip this add the following code
int minimAge = reader.nextInt();
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()
I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.
I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.
import java.io.IOException;
import java.util.Scanner;
public class ScannerTest {
static String name;
static Scanner in = new Scanner(System.in);
static int choice;
public static void main(String[] args) {
while(choice != 5){
System.out.print("\nEnter Choice :> ");
choice = in.nextInt();
if(choice == 1){
try{
printName();
}
catch(IOException e){
System.out.println("IO Exception");
}
}
}
}
private static void printName()throws IOException{
System.out.print("\nEnter name :> ");
name = in.next();
//name = in.nextLine();
if (name != null){
System.out.println(name);
}
}
}
Try this instead: add name = in.nextLine(); after choice = in.nextInt();.
Then try replacing name = in.next(); with name = in.nextLine();
Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the \n. We then consume the rest of the string with nextLine().
The second nextLine() is then used to get your string parameters.
The problem is easy: when you prompt the user to enter his/her choice, the choice will be an int followed by a new line (the user will press enter). When you use in.nextInt() to retrieve the choice, only the number will be consumed, the new line will still be in the buffer, and, so, when you call in.nextLine(), you will get whatever is between the number and the new line (usually nothing).
What you have to do, is call in.nextLine() just after reading the number to empty the buffer:
choice = in.nextInt();
if (in.hasNextLine())
in.nextLine();
before to call name = in.next(); do this in = new Scanner(System.in);
the object need rebuild itself because already has value.
good luck