1

I am new to Java and would like to ask you a question.

I have written the below code where "numOfThreads" should be assigned a valid int value by the user through the Console.

However, I would like to achieve a result where if the input is incorrect and we go in the catch block, the user should be re-prompted to enter "numOfThreads" until it is of correct type and range.

For some reason I seem to go into infinite loop. Can you please assist? Thanks :)

import java.util.Scanner;

public class Main {

    public static void main(String args[]){

        int numOfThreads;
        boolean promptUser = true;

        Scanner keyboard = new Scanner(System.in);

        while (promptUser)
        {
            try{
                numOfThreads = keyboard.nextInt();
                promptUser = false;
            }
            catch(Exception e){
                System.out.println("Entry is not correct and the following exception is returned: " + e);
                numOfThreads = keyboard.nextInt(); // DOES NOT SEEM TO BE ASKING FOR A NEW INPUT
            }
        }
    }
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
drdisp
  • 19
  • 1
  • 1
    If `nextInt()` throws an exception, it doesn't consume the token... so calling `nextInt` again is just going to throw again. – Jon Skeet Sep 14 '16 at 12:46
  • Your try/catch is pretty useless... What if they input a wrong input when you reprompt? – Andrew Li Sep 14 '16 at 12:47

1 Answers1

3

it doesn´t because nextInt tries to consume the last token. When there is an invalid input it can´t consume it. As a result a following nextInt call wont be able to consume it either. write a keyboard.nextLine before numOfThreads = keyboard.nextInt(); and you are fine.

catch(Exception e){
    System.out.println("Entry is not correct and the following exception is returned: " + e);
    // this consumes the invalid token now
    keyboard.nextLine();
    numOfThreads = keyboard.nextInt(); // It wasn´t able to get the next input as the previous was still invalid
    // I´d still rewrite it a little bit, as this keyboard.nextInt is now vulnerable to throw a direct exception to the main
}
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33