Garik Garik - 3 months ago 5
Java Question

how to check whether the input is integer or not

I a making a program that will ask an int input from user and check whether user input is an integer or not. If no the program asks for an input tile it gets a integer.

Scanner in = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
int num;
if (in.hasNextInt()){
num =in.nextInt();
if(num % 2 == 0){
System.out.print("this is even!!");
} else{
System.out.println("this is odd!!");
}
} else {
System.out.print("pleas enter an integer only!!!");
num = in.nextInt();
if(num % 2 == 0){
System.out.print("this is even second check!!");
} else{
System.out.println("this is odd second check!!");
}
}


here is the code but i have some mistakes in there. it brings an error when input is not an int. pleas help with this, thanks in advance!

Answer

Try the below code, it will end only if its a valid Integer otherwise it will keep asking for Integer and I think you are looking for the same.

public void checkInt() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Eneter a nuber here:");
    try {
        int num = scanner.nextInt();
        if (num % 2 == 0) {
            System.out.print("this is even!!");
        } else {
            System.out.println("this is odd!!");
        }
    } catch (InputMismatchException e) {
        System.out.println("pleas enter an integer only!!!");
        checkInt();
    }
}
Comments