-1

I'm attempting to make a java function that returns an int inputted by the user, but won't return until the user inputs a valid number. Here's my initial model of the function:

    public int getChoice(){
        try{
            return scan.nextInt();
        }catch(Exception e){
            return getChoice();
        }
    }

scan is declared by Scanner scan = new Scanner(System.in);

This function resulted in a Java.lang.stackOverflowError(hmm... this seems an appropriate website for that...). I figure this is because the function is being constantly called.

I've considered somehow using Integer.valueOf(scan.nextLine())', but the reason I haven't really done anything with it is because at some points, and I can't figure out what determines whether this happens or not, but pressing 'Enter' when the program is calling nextLine() will skip the next nextLine(). I can't really figure out a way around that.

So if anyone could possibly provide me with a Java function that will loop until the user inputs a valid integer, then return that integer, please do so, thank you.

user2649681
  • 600
  • 5
  • 19
  • You can rewrite your code without recursion to see what happens: stick it in a `while(true)` loop and remove the call to `getChoice()` - the return will break the loop and if there is an exception it will just repeat. – John3136 Jan 26 '15 at 22:18

1 Answers1

1

You are getting a bad recursion because the getChoice call inside catch block. To repeat the code indefinitely until the user gives you a valid number use while(true) infinite loop. The code you have to read the line and convert it to Integer it is just fine.

public int getChoice() {       
    while (true) {
        try {                                
            return Integer.valueOf(scan.nextLine());
        } catch (Exception e) {
            System.out.println("Enter a valid number");
        }
    }
}
enrique7mc
  • 837
  • 9
  • 12