Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

java - How can I check for invalid input and loop until the input is valid?

I am trying to find the smallest number in the list from user input. I need to ask the user how many numbers are going to be in the list (and only accept positive numbers and no letters) and then ask them what the numbers are in the list (accepting only numbers). How can I check for this and keep looping until the numbers are valid?

public class SmallestInt {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {


        // Initialize a Scanner to read input from the command line
        Scanner input = new Scanner(System. in );
        int totalIntegers = 1;
        int num = 0;
        int smallest = 0;
        boolean inputValid = false;

        /* Prompt the user and validate their input to ensure they've entered a positive (greater than zero) integer. Discard/ignore any other data.
         */

        while (!inputValid)

        {
            System.out.print("How many integers shall we compare? (Enter a positive integer): ");

            try {
                totalIntegers = input.nextInt();
                inputValid = true;

            } catch (NumberFormatException e) {
                System.out.println("Invalid input!");
            }


            /* Read in the candidates for smallest integer
             * Validate this input as well, this time ensuring that the user has provided a valid int (any int will do at this point) and discarding any other data
             */
            for (int ii = 1; ii <= totalIntegers; ii++) {

                // Prompt 
                System.out.print("Enter value " + ii + ": ");

                num = input.nextInt();

                if (ii == 1) smallest = num;
                else if (num < smallest) smallest = num;

            }


            // display smallest int

            System.out.println("The smallest number entered was: " + smallest);
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since this is clearly a homework / learning exercise, I won't give you code. You will learn more if you do the actual coding for yourself.

Once you have fixed the problem with the loop nesting ...

There are three problems with this code:

while (!inputValid) {
    System.out.print("How many integers? (Enter a positive integer): ");
    try {
        totalIntegers = input.nextInt();
        inputValid = true;
    } catch (NumberFormatException e) {
        System.out.println("Invalid input!");
    }
}

First problem is that you are catching the wrong exception. Read the javadoc.

The second problem is that if nextInt fails (due to a problem parsing the integer) it puts the scanner's input cursor back to where it was before the call. And when you call it again (in the next loop iteration) it will attempt to read same "bad" number again, and again, and again, ...

You have to tell the scanner to skip over the invalid line of input so that it can read the user's next attempt.

The third problem is that you don't check that the number you just read is positive!!

Final hint: consider using while (true) and a conditional break, instead of while (condition). I think it gives a more elegant solution.


@Kick Buttowski's solution deals with the bad input skipping by creating a new Scanner on each loop iteration. Apparently it works ... but I have some doubts1 that you can rely on this always working. IMO a better solution would be to use one Scanner throughout, and use a nextLine() call to read and discard the characters up to and including the end of line.


1 - My main concern is that when you leak a Scanner that it might (in some implementations) close the underlying input stream in a finalizer. If that actually happened, then the application would stop accepting input. The current implementation does not do this, but this is not clearly specified (AFAIK).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...