1

First of all I want to address that I'm a beginner with exceptions, therefore I'm having trouble.

I'm working on a code that tries to detect if a number is an integer or not using try catch. So if the user puts something that's not an integer, let's say the letter 'a', I want the code to ask for another value. In other words, for anything that's not an integer I want to ask the user to put another value.

Code 1:

I've tried to use a detector to see if the user input is and Integer or not

static Scanner kbd = new Scanner(System.in);
    public static void LecturaValidada(){
        int n;
        int esEntero=-1;
        while(esEntero<=0){
            try{
                System.out.print("Introduce un valor: ");
                n = kbd.nextInt();
                esEntero=1;
            } catch(InputMismatchException e){
                System.out.println("Usted ha introducido un caracter/frase, no un entero.");
                esEntero=-1;
            } catch(NumberFormatException e){
                System.out.println("Usted ha introducido un número que no es un entero.");
                esEntero=-1;
            }
        }
        
        System.out.println("Usted SI ha introducido un entero.");
  }

Code 2: Same as Code 1, but with do while

public static void LecturaValidada(){
        int n;
        int esEntero=-1;
        do{
            try{
                System.out.print("Introduce un valor: ");
                n = kbd.nextInt();
                esEntero=1;
            } catch(InputMismatchException e){
                System.out.println("Usted ha introducido un caracter/frase, no un entero.");
                esEntero=-1;
            } catch(NumberFormatException e){
                System.out.println("Usted ha introducido un número que no es un entero.");
                esEntero=-1;
            }
        } while(esEntero == -1);
        
        System.out.println("Usted SI ha introducido un entero.");
}

I've also been playing with boolean values

In the end, I get 1 of 2 outputs:

  • Output 1: It will detect that the value put by the user is not an integer and it will not ask for another value
  • Output 2: It will constantly appear this message: "Introduce un valor: Usted ha introducido un caracter/frase, no un entero."
CDAMXI
  • 35
  • 5
  • You may be interested in: [How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner](https://stackoverflow.com/q/3572160), and [How to use Scanner to accept only valid int as input](https://stackoverflow.com/q/2912817), [Validating input using java.util.Scanner](https://stackoverflow.com/q/3059333) – Pshemo May 01 '23 at 11:49

3 Answers3

3

here is simple code to handle this

public static void main(String[] args) {
        Scanner kbd = new Scanner(System.in);

        int inputNum = 0;
        boolean isIntValue = false;

        while (!isIntValue) {
            try {
                System.out.print("Enter an Integer Value: ");
                String input = kbd.nextLine();
                inputNum = Integer.parseInt(input);
                isIntValue = true;
            } catch (NumberFormatException e) {
                System.out.println("Invalid input! Please enter an Ingeger Value.");
            }
        }

        System.out.println("You entered the Value " + inputNum + ".");
    }
Vasim Hayat
  • 909
  • 11
  • 16
0

I agree with @Vasim Hayat answer. There is also an alternative solution, without using a while loop, but using recursion (calling the same method by itself):

public static void main(String[] args) {
    Scanner scn = new Scanner(System.in);

    int inputNum = getIntValue(scn);
    
    System.out.println("You entered the Value " + inputNum + ".");  
}

private static int getIntValue(Scanner scn) {
    System.out.println("Please enter an Integer Value:");
    
    try {
        return Integer.parseInt(scn.nextLine());
    } catch (NumberFormatException e) {
        System.out.println("Invalid input!");
        return getIntValue(scn);
    }
}
0

You have to consume the nextline character left by the nextInt() call.

catch(InputMismatchException e)
{
    kbd.nextline()
    System.out.println("Usted ha introducido un caracter/frase, no un entero.");
    esEntero=-1;
}

see this How can I clear the Scanner buffer in Java?

st3ems
  • 39
  • 3