0

I have a separate thread class and below is the run method,

    @Override
    public void run() {

        Scanner scanner = new Scanner(System.in);
        int iRequestType = 0;
        int iRequestId = 0;

        while (!exit){
            try {
                System.out.print("\nRealTime - 1\nHttpUrl - 2\nSelect one : ");
                iRequestType = scanner.nextInt(); //it will wait here after the exception occurs

                System.out.print("\nEnter Request ID : ");
                iRequestId = scanner.nextInt();

                if(iRequestType == 1 && !map_RealTimeRequests.isEmpty()){
                    sendRealTimeRequest(iRequestId);
                } else if (iRequestType == 2 && !map_HttpUrlRequests.isEmpty()){
                    sendHttpUrlRequest(iRequestId);
                } else if(iRequestType > 2) {
                    System.out.println("Invalid List Number");
                }else {
                    System.out.println("Empty List");
                }
            } catch (InputMismatchException e){
                System.out.println("Invalid request type or ID : " + e);
                scanner.close();
                scanner = new Scanner(System.in);
            }

        }
    }

If I enter numbers, the program works fine. When I enter a character, it goes to the catch block and and execute the lines within it as expected. Once the execution of catch block completes, it will iterate again and ask for the keyboard inputs. But when I try to enter a value (a number or a character), it does not read anything and keep waiting without executing the next lines. What I want to do is, ask the user to enter a number and if the user enter a character, print an error message in console and iterate the while loop again. How can I solve this issue? Thanks in advance!

9
  • 1
    Check this : stackoverflow.com/questions/2496239/… Commented May 26, 2020 at 4:59
  • 1
    Check this : stackoverflow.com/questions/2912817/… Commented May 26, 2020 at 5:00
  • 4
    Does this answer your question? How to use Scanner to accept only valid int as input Commented May 26, 2020 at 5:01
  • Please clarify your question. But when I try to enter a value (even a number)... what's the value that triggers the problem? ...keep waiting without executing the next lines so on which line it get's stuck. And in which way do you think it's related to an exception? Try to reduce your code as in How to create a Minimal, Reproducible Example. Commented May 26, 2020 at 5:04
  • Exception should trigger if the user enter an character instead of a number. The problems occurs after an exception triggered. If I enter a character (let's say "q"), it triggers the exception and execute the catch block. Then it will iterate again and waits for user inputs (I have added a comment). Then it should execute the rest of the lines if I enter the correct value(a number). But without executing the rest of the code, it waits @IvoMori Commented May 26, 2020 at 5:31

1 Answer 1

0

You should not call scanner.close() because that closes System.in. You don't want to close System.in you just want to clear out the buffer. You can do that by replacing the scanner as you did (without the close() call), or you can call nextLine() if it's single-line input like this:

} catch (InputMismatchException e){
  System.out.println("Invalid request type or ID : " + e);
  scanner.nextLine();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Doing this change to the OP's code fixes the Exception in thread "Thread-3" java.util.NoSuchElementException (uncaught exception) as described in my comment.
I changed the catch to accept any Exception object
I found that the Exception in thread "Thread-3" java.util.NoSuchElementException is triggered by the OP's scanner.close(); statement in the catch block. Given the OP's original code and just changing the catch InputMismatchException to Exception results in an infinite-loop. The crucial point is as you stated "not to call scanner.close()". So your original answer, catch (InputMismatchException e is actually "fine", i.e it doesn't make a difference in this case.
makes sense - I put the example back and avoiding .close should solve things

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.