I want to separate text lines by user's input of pressing ENTER button. Though if I press ENTER once it gives me all the lines at one moment. I suppose that Scanner just "keeps in mind" my first input and counts it for all input.hasNextLine()
commands below.
Here's the code:
System.out.println("text");
input.hasNextLine();
System.out.println("text");
input.hasNextLine();
System.out.println("text");
input.hasNextLine();
System.out.println("text");
input.hasNextLine();
System.out.println("text");
Is there any way to cut scanner reading stream without confusing it with buffer variables (e.g setting string variable to input's data and then comparing it with "if" statement)?
No, there is no way using the hasNextLine()
method itself, if that's what you want.
It is because the scanner doesn't advance past any input when you call the hasNextLine()
method, you are simply asking the scanner instance if it has another line in the input of this scanner.
To achieve your intended behaviour, you need to advance the scanner past the current line by calling the nextLine()
method. You can choose to store the read input or ignore it.
Scanner input = new Scanner(System.in);
System.out.println("text");
input.nextLine();
System.out.println("text");
input.nextLine();
System.out.println("text");
input.nextLine();
System.out.println("text");
input.nextLine();
System.out.println("text");