1

I would like to read an integer value of the user's choice and entry, but do not want the exception to crash the program if the user makes a mistake and enters an unreadable value instead. To this end, I have written a while loop containing a try/catch sequence which is meant to return, in the event of an invalid entry, a brief statement explaining the user's error and a prompt to try again.

When I run the program with this code, although the Scanner object I am using to read the user's input seems to work correctly during the first pass of the loop, in subsequent passes the try statement is automatically failed without waiting for new input, which naturally leads to an interminable series of error messages and prompts.

Here is my code:

        Scanner tScan = new Scanner(System.in);
        int gChoice = 0;
        boolean gValid = false;
        while (!gValid)
        {
            try{
                gChoice += tScan.nextInt();
                gValid =true;
            } catch(Exception e){
                System.out.println("Input rejected. Please try again:");
            }
        }

The program pauses at gChoice += tScan.nextInt(); and will only proceed when the user has entered some data and tScan has attempted to harvest an integer from it. If it cannot find an integer, it proceeds to the catch statement, returns to the start of the loop, notes that gValid is still not true, enters the try statement, reads the line gChoice += tScan.nextInt(); but does not pause for user input, fails to assign gChoice an integer from tScan, proceeds to the catch statement and so on.

I would appreciate any advice on what I might be doing wrong or how else I may avoid this problem.

Edit: Now resolved, thanks to Greg.

Bibliophael
  • 177
  • 11

1 Answers1

1

You need to clear the bad input from the scanner. Try adding tScan.next(); to the catch block.