-1

I have this code:

public class SimpleTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter: ");

        String s = "";
        while (scanner.hasNext())  {
            s += scanner.next();
            System.out.println(s);
        }

        System.out.println("Result: " + s);
    }
}

My code shows:

enter image description here

While Result: line never gets printed.

How do I fix it? (Without using scanner.nextLine, .split() or a different while condition like whle (!input.equals("quit"))

parsecer
  • 4,758
  • 13
  • 71
  • 140
  • I don't think you can with `System.in` not without doing something really weird like closing the `System.in` stream (which I think would be very bad). Data from system is the user typing, normally you tell them to type five things (or whatever number) then collect that many and go on without check for "more." – markspace Mar 22 '21 at 19:34
  • P.S. `nextLine()` is exactly what I would suggest in this circumstance. Why do you not want to use it? – markspace Mar 22 '21 at 19:35
  • https://stackoverflow.com/questions/10490344/how-to-get-out-of-while-loop-in-java-with-scanner-method-hasnext-as-condition possible duplicate – Lakshya Srivastava Mar 22 '21 at 19:36
  • 4
    Does this answer your question? [How to get out of while loop in java with Scanner method "hasNext" as condition?](https://stackoverflow.com/questions/10490344/how-to-get-out-of-while-loop-in-java-with-scanner-method-hasnext-as-condition) – Lakshya Srivastava Mar 22 '21 at 19:38
  • 1
    You could input EOF to signal "no more data here" after the last number. (Ctrl+D on linux, I belive Ctrl+Z on Windows) – Poohl Mar 22 '21 at 19:41

1 Answers1

1

When scanning a file eventually the scanner gets to the end of stream marker and so it knows there's no more data to scan and so hasNext() returns false. However, when scanning from the command line there is no end of stream marker so hasNext() bocks waiting for the next chunk of data (or the end of stream marker).

You need to decide how you are going to end command line input, eg is it on entering a specific number of item or putting your input followed a specific keystroke/keyword eg END, EOF, STOP etc. You then need to add code to your while loop to find the end of input marker and exit the loop.

momolechat
  • 155
  • 11