Search code examples
javarecursiontry-catchnumberformatexception

NumberFormatException in try catch recursion doesn't work after 2 or more "mistakes"


So I am trying to write a method that checks if scanner input is an int, and loops errormessage until the user inputs an int. The method below works aslong as the usser doesn't give more than 1 wrong input. If I type muliple letters and then an int, the program will crash. I think it might have something to do with my try catch only catching 1 exception but not sure, and cant seem to get it to work. Does anyone know how I can fix this?

calling on method:

System.out.println("Write the street number of the sender: ");
int senderStreetNumber = checkInt(sc.nextLine);

method:

public static int checkInt (String value){
  Scanner sc = new Scanner(System.in);
  try{
    Integer.parseInt(value);
  } catch(NumberFormatException nfe) {
    System.out.println("ERROR! Please enter a number.");
    value = sc.nextLine();
    checkInt(value);
  }
  int convertedValue = Integer.parseInt(value);
  return convertedValue;
}

Solution

  • Something like this. Did not code it in an IDE, just from brain to keyboard. Hope it helps. Patrick

    Scanner sc = new Scanner(System.in);
    
    int senderStreetNumber;
    boolean ok = false;
    
    while(!ok) {
        System.out.println("Write the street number of the sender: ");
        try {
            senderStreetNumber = Integer.parseInt(sc.nextLine());
            ok = true;
        } catch (NumberFormatException nfe) {
            System.out.println("ERROR! Please enter a number.");
        }
    }