-1

I want to say enter an integer when someone trying to enter a string in this code.

Can you help me?

Here is my code:

        import java.util.Scanner;
        public class kl {
            public static void main(String[] args) {
                boolean primen = true;
                Scanner input = new Scanner(System.in);
                System.out.print("Please enter a positive integer that is prime or not : ");
                int ncheck = input.nextInt();
                if (ncheck < 2) {

                    primen = false;

                }
                for (int i = 2; i < ncheck; i++) {
                    if (ncheck % i == 0) {
                        primen = false;
                        break;
                    }
                }
                if (primen == true) {
                    System.out.println(ncheck + " is a prime number.");
                }
                else {
                    System.out.println(ncheck + " is not a prime number.");
                }
            }
        }
demongolem
  • 8,796
  • 36
  • 82
  • 101

2 Answers2

0

You can find your solution here: Exception handling, Or use codes below

Here is your complete code:

while(true){
System.out.print("Please enter a positive integer that is prime or not : ");
try{
   int i = input.nextInt();
   break;
}catch(InputMismatchException e){
   System.out.print("Wrong type input, pls try again!");
   input.nextLine(); \\ prevent infinite loop
}

You can see: I use a Exception handle processor to catch the InputMismatchException and print on console the message. You can replace InputMismatchException by Exception. It's largest Exception Handler class in java

Wing
  • 552
  • 3
  • 13
0

There are two approaches you can use with Scanner.

  • Call nextInt() and then catch and handle the InputMismatchException that you will get if the next input token isn't an integer.

  • Call hasNextInt(). If that returns true then call nextInt().

In either case, if you expected an integer and the user entered something else, then neither nextInt() or hasNextInt() will "consume" the unexpected characters. So if you want the user to try try again, you need to call nextLine() which will read all remaining characters on the line. You will typically discard them.

For more information on handling exceptions:

For more information on using Scanner:

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096