简体   繁体   中英

Java Scanner receives nonexistent input

I have a loop which breaks upon receiving the correct input from the console. I am using Scanner to read in a String from System.in, which seems to be what's giving me trouble. Here is my code:

boolean loop = true;

while(loop) {
    try {
        System.out.println("Enter an input (\"input a\" or \"input b\"): ");

        String input = scanner.nextLine();

        System.out.println("");

        if (input.equals("input a")) {  
            System.out.println("Answer to input a.");
        } else if (input.equals("input b")) {   
            System.out.println("Answer to input b.");
        } else {
            throw new IllegalArgumentException();
        }

        loop = false;
    } catch (InputMismatchException e) {
        System.out.println(e.getMessage());
        System.out.println("");
    } catch (IllegalArgumentException e) {
        System.out.println("Input not recognized.  Please enter a valid input.");
        System.out.println("");
    }
}

When this is called, it loops once without even waiting for input from the user, then actually stops and does what it is supposed to the second time around. IE, the output for this, without the user giving any input at all, is:

Enter an input ("input a" or "input b"):

Input not recognized.  Please enter a valid input.

Enter an input ("input a" or "input b"):

If I give it a bad input (so that it loops and asks again), it does the same thing where it loops twice before waiting. I have no idea why.

Why is this happening, and what should I do to avoid it?

EDIT: Test scenarios after hasNext check:

Scenario A:

Enter an input ("input a" or "input b"): input a //my input

Input not recognized.  Please enter a valid input.

Enter an input ("input a" or "input b"): //no input given here

Answer to input a.

Scenario B:

Enter an input ("input a" or "input b"): ddd //my input

Input not recognized.  Please enter a valid input.

Enter an input ("input a" or "input b"): //no input given here

Input not recognized.  Please enter a valid input.

Enter an input ("input a" or "input b"): input b //my input

Answer to input b.

The code which produces this:

boolean loop = true;

while(loop) {
    if (scanner.hasNext()) {
        try {
            System.out.println("Enter an input (\"input a\" or \"input b\"): ");

            String input = scanner.nextLine();

            System.out.println("");

            if (input.equals("input a")) {  
                System.out.println("Answer to input a.");
            } else if (input.equals("input b")) {   
                System.out.println("Answer to input b.");
            } else {
                throw new IllegalArgumentException();
            }

            loop = false;
        } catch (InputMismatchException e) {
            System.out.println(e.getMessage());
            System.out.println("");
        } catch (IllegalArgumentException e) {
            System.out.println("Input not recognized.  Please enter a valid input.");
            System.out.println("");
        }
    }
}

I tried out the code you've wrote down in your question, as a single question, but I can't find any problem with it at all. However, I think I know just the answer.

If you did any other input before this with primitive types or just next(), you need to flush the newline character that unfortunately those next methods leave behind. To do this, just call " scanner.nextLine() " before the statement where the method returns the inputted string and assigns it to input .

You want to make sure that you call in the method as separate; you know, on its own. It's best if you put it in your while loop at the top before you enter so that way for every iteration, the newline character is cleared. The statement will then get rid of the newline character and thus the input buffer is empty. Once that's cleared out, you can finally input your string at your first loop iteration.

How's that for an answer? Try it out and let me know if it works!

You should first check if the user has enetered any data :

if(scanner.hasNext())
{
   // code logic
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM