#Enter key instead of specific word to stop scanning

16 messages · Page 1 of 1 (latest)

candid hatchBOT
#

This post has been reserved for your question.

Hey @raw sage! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

#

Please format your code to make it more readable.
For java, it should look like this:
```​​`​java
public void foo() {

}
​`​```

shut storm
#

Java can't detect key strokes on the console.
But you could stop when the user enters an empty line.
For that you'd need to use nextLine() rather than than next(), and check for empty line read.
(That means you can never call anything but nextLine() on your Scanner. It's either nextLine() or the others. No mixing them.)

raw sage
shut storm
#

"add the numbers to the list"?

raw sage
shut storm
#

I see

#

And, errm, you gave me these lines,

#

and you need me to tell you how to replace next() with nextLine()?

shut storm
#

String token = cons.nextLine(); numbers.add(Integer.parseInt(token));

raw sage
terse juncoBOT
#
        List<Integer> numbers = new ArrayList<Integer>();
        Scanner cons = new Scanner(System.in);
        System.out.println("Insert numbers");
        while (cons.hasNext()) {
            String token = cons.next();

            try {
                numbers.add(Integer.parseInt(token));
            } catch (NumberFormatException nfe) {

            }
            if (cons.nextLine().isEmpty()) { 
                break;
            }
        }
        return numbers;
    } ```

This message has been formatted automatically. You can disable this using /preferences.

shut storm
#

That's not what I said

raw sage
#

\close