I tried to create an if statement inside my code to print a message if the user entered a wrong type of input rather than showing the "InputMismatchException" message by the compiler.

import java.util.*;

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

        //Prompt the user for how many integers are going to be entered

        System.out.print("*Please write how many numbers are going to be entered: ");
        int a = scan.nextInt();
        int[] n = new int[a];

        if(a >= 0)
            for(int i = 0; i < a; i++) {
                System.out.print("*Please enter an enteger: ");
                n[i] = scan.nextInt();
            }//for
        else
            System.out.print("*Sorry your entery was not correct. Please enter digits only. ");

    }//main
}//Pr8
3

There are 3 answers

1
Ankur Singhal On BEST ANSWER

check for scan.hasNextInt(), this will work for you.

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

    // Prompt the user for how many integers are going to be entered

    System.out.print("*Please write how many numbers are going to be entered: ");

    if (scan.hasNextInt()) {
        int a = scan.nextInt();
        int[] n = new int[a];

        for (int i = 0 ; i < a ; i++) {
            System.out.print("*Please enter an enteger: ");
            if (scan.hasNextInt()) {
                n[i] = scan.nextInt();

            } else {
                System.out.print("*Sorry your entery was not correct. Please enter digits only. ");
                break;
            }
        }// for
    } else {
        System.out.print("*Sorry your entery was not correct. Please enter digits only. ");
    }

}
0
MH2K9 On

You can use try{}catch(){} to prevent from exception. Example:

int a = 0;
try{
    a = scan.nextInt();
}catch(Exception ex){
    System.out.println("Show you message");
}

In for loop in your code

try{
    n[i] = scan.nextInt();
}catch(Exception ex){
    System.out.println("Show you message");
}
0
guribe94 On

Don't use an if statement to do this use a try/catch, it does exactly what you want. Here is a tutorial I found on Google for you to take a look at. For you it would look something like this:

if (a >= 0)
      for (int i = 0; i < a; i++){
      System.out.print("*Please enter an enteger: ");
      try{
    //Try to get an int as input, continue if proper input is given
    n[i] = scan.nextInt();
    }catch(Exception e){
    //Handle your error here
    }
    }

This captures all exceptions but if you only want to capture InputMismatchExceptions then you could do this:

if (a >= 0)
      for (int i = 0; i < a; i++){
      System.out.print("*Please enter an enteger: ");
      try{
    //Try to get an int as input, continue if proper input is given
    n[i] = scan.nextInt();
    }catch(InputMismatchException e){
    //Handle your error here
    }
    }