1

I am attempting to use the Scanner class to read several inputs from the user. The inputs are each separated by a single space and should be on one line.

At first, I tried simply getting rest of the line immediately after the prompt:

Scanner scan = new Scanner(System.in);
System.out.print("Enter inputs: ");
String input = scan.next();
System.out.println(input);

However, when I enter (for example) "5 6 7", only 5 is output. This is expected, because tokens in a scanner are demarcated by spaces by default. But when I try

Scanner scan = new Scanner (System.in);
System.out.print("Enter inputs: ");
String input = "";
while (scan.hasNext)
     input += scan.next();

it enters into a loop where no matter what I enter, whether it be numerical, alphabetical, or new lines, it continues to take input instead of moving on. I don't understand why it's doing this, as it seems no different from the countless examples I found online.

Utlimately, my question is, how do you stop the hasNext() loop?

Edit: To clarify, it should only take numeric input, so I can't take another phrase like "exit".

avandesa
  • 178
  • 1
  • 6

0 Answers0