A student of mine is having an issue with the Eclipse terminal, for which I couldn't find an answer. The goal was to read an integer first, then a line of text, as the following code shows:
package testequals;
import java.util.Scanner;
public class TestEquals {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter an integer: ");
if (reader.hasNextInt()) {
int value = reader.nextInt();
System.out.println("The value is " + value);
}
// Empty the buffer of either :
// The '\n' left by nextInt();
// The wrong characters entered
reader.nextLine();
System.out.print("Enter '1': ");
String x = reader.nextLine();
// If we entered 1 it prints 1 ...
System.out.println(x);
// But the following condition is still false ...
if (x.equals("1")) {
System.out.println("OK");
}
reader.close();
}
}
The main issue is that it works on my computer, but not on his. As the comments indicates, the first reading works fine, but not the second one. It seems that there is something left in the Scanner object reader
after the first input, and that the String we obtain on the second input is tainted.
On the second input, if the user really entered 1 and we check with the Eclipse debugger, it shows that the String really contains "1". If we print it, it really prints "1" in the terminal, without a trailing '\n' nor anything else. But still, the "equals()" test still returns false.
If we replace the second input with a call to nextInt() instead of nextLine(), it crashes with an InputMismatch exception, showing that there is something left in the buffer of reader
even after the instruction to empty the buffer. Which, I know, doesn't really empty the buffer, but still, I wonder what could be left in that buffer!
Because if we re-create the reader
just before the second input with nextInt() as follows:
reader = new Scanner(System.in);
It resolves the issue. So it really shows that it is a buffer issue. So fine, we got a workaround, but I'm still confused as to why this issue happens in the first place.
So, I thought that maybe it was en encoding issue, for instance where the Java code expects Linux-style line delimiter ('\n') but gets Windows-style line delimiter ("\n\r") but I'm not sure.
The student switched from a CP-1252 file encoding to UTF-8 but it did not resolve the issue (on Eclipse, in Windows->Preferences->General->Workspace->Text file encoding). On my end, I switched from Linux-style line delimiter to Windows-style line delimiter but I could not replicate his issue (on Eclipse, in Windows->Preferences->General->Workspace->New text file line delimiter).
The student uses Eclipse 4.22.0 (2021-12) and is on Windows, while I use the same Eclipse version but I am on Linux.
Any idea what I should look for?