I have the following method:
private String doEntryScan(InputStream stream)
{
try (Scanner scanner = new Scanner(stream)) // Reading from System.in
{
String readString = scanner.nextLine();
if (readString.isEmpty())
{
readString = "\n";
}
scanner.nextLine(); //consume carriage returns if they remain
scanner.close();
return readString;
}
}
The idea is that the user can hit enter to accept defaults. Or they can enter something. If I include the line
scanner.nextLine(); //consume carriage returns if they remain
the method hangs at that point, presumably waiting for more input. If I don't have that line, I get a NoSuchElementException the next time I call this method. I'm assuming this is because there's a carriage return in the stream.
So how does one get around this? scanner.hasNext() doesn't help because it ALSO "sometimes" blocks. By the way, in practice InputStream is System.in.