scanning a double and char value at same time

neznamy03 :

Scanner userInput = new Scanner(System.in); do { System.out.println(userInput.nextDouble()); } while(true);

what to do, when I'm printing double numbers but I want to break this loop after a user enters 'k' character?

Samuel Silver Moos :

You can validate what next input is, a possible solution for your case would be:

boolean doscan=true;
Scanner userInput = new Scanner(System.in);
do {
    if(userInput.hasNextDouble()) {
        System.out.println(userInput.nextDouble());
    } else if (userInput.next().equals("k")){
        doscan=false;
    }
} while(doscan);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216284&siteId=1