Using scanner.nextLine() [duplicate]
Solution 1:
I think your problem is that
int selection = scanner.nextInt();
reads just the number, not the end of line or anything after the number. When you declare
String sentence = scanner.nextLine();
This reads the remainder of the line with the number on it (with nothing after the number I suspect)
Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.
Solution 2:
Rather than placing an extra scanner.nextLine()
each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)
import java.util.Scanner;
class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\n");
System.out.print("Enter an index: ");
int index = scanner.nextInt();
System.out.print("Enter a sentence: ");
String sentence = scanner.next();
System.out.println("\nYour sentence: " + sentence);
System.out.println("Your index: " + index);
}
}
Thus, to read a line of input, you only need scanner.next()
that has the same behavior delimiter-wise of next{Int, Double, ...}
The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3
, 3<space>
and 3<space>whatever
while the former only accepts 3
on a line on its own
Solution 3:
It's because when you enter a number then press Enter, input.nextInt()
consumes only the number, not the "end of line". Primitive data types like int, double etc do not consume "end of line", therefore the "end of line" remains in buffer and When input.next()
executes, it consumes the "end of line" from buffer from the first input. That's why, your String sentence = scanner.next()
only consumes the "end of line" and does not wait to read from keyboard.
Tip: use scanner.nextLine()
instead of scanner.next()
because scanner.next()
does not read white spaces from the keyboard. (Truncate the string after giving some space from keyboard, only show string before space.)
Solution 4:
Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.