-2

I try to solve the next task: 1. Asking the user for a positive integer. 2. If the user adds a negative or a real number or both, the next error message should be displayed on the console: "wrong input".

That is what I have done so far.

Scanner sc = new Scanner(System.in);
System.out.print("Please, add a positive integer! ");
int num = sc.nextInt();
if (num < 0) {
    System.out.println("wrong input");
}

Everything works well, except I cannot make sure that the user receives the error message if he/she doesn't type an integer but a real number. In this case, the program goes wrong.

I would appreciate the help.

Backslash
  • 15
  • 5

3 Answers3

1
import java.util.Scanner;
import java.util.InputMismatchException;

public class ScanTest
{
  public static void main(String[] args)
  {
    Scanner sc = new Scanner(System.in);
    boolean badInput = true;
    int num;

    // Keep asking for input in a loop until valid input is received

    while(badInput)
    {
        System.out.print("Please, add a positive integer! ");

        try {
            num = Integer.parseInt(sc.nextLine());
            // the try catch means that nothing below this line will run if the exception is encountered
            // control flow will move immediately to the catch block
            if (num < 0) {
                System.out.println("Please input a positive value.");
            } else {
                // The input is good, so we can set a flag that allows us to exit the loop
                badInput = false;
            }
        }
        catch(InputMismatchException e) {
            System.out.println("Please input an integer.");
        }
        catch(NumberFormatException e) {
          System.out.println("Please input an integer.");
        }
      }
    }
}
MarsAtomic
  • 10,436
  • 5
  • 35
  • 56
1

Occasionally I find it easier to read in a string and then try and parse it. This presumes you would like to repeat the prompt until you get a valid number.

Scanner sc = new Scanner(System.in);
int num = -1;
while (num < 0) {
    System.out.print("Please, add a positive integer! ");

    String str = sc.nextLine();
    try {
        num = Integer.parseInt(str);
    } catch (NumberFormatException e) {
         System.out.println("Only integers are accepted.");
         continue;
    }
    if (num < 0) {
        System.out.println("Input is < 0.");
    }
}

Read about NumberFormatException here.

WJS
  • 36,363
  • 4
  • 24
  • 39
0

When you're using Scanner.nextInt() the input is expected to be an integer. Inputting anything else, including a real number, will throw an InputMismatchException. To make sure invalid input doesn't stop your program, use a try/catch to handle the exception:

int num;
try {
    num = sc.nextInt();
    // Continue doing things with num
} catch (InputMismatchException e) {
    // Tell the user the error occured
}
Marsroverr
  • 556
  • 1
  • 6
  • 23