-1
System.out.println("Insert first number : ");
Scanner ad = new Scanner(System.in);
int y = ad.nextInt();
System.out.println("Insert Second Number: ");
Scanner er = new Scanner(System.in);
int x = er.nextInt();

int z;
z = x + y;

if (z > 10) {
    System.out.println(z + " is greater than 10");
} else if (z < 9) {
    System.out.println(z + " is less than 10");
} else {
    System.out.println(z + " is equal to 10");
}

I want the output of each if statements to be error when I put character instead of numbers. And make an output appear that the character I have entered is invalid.

Joulukuusi
  • 2,440
  • 6
  • 31
  • 47
alkhemet
  • 3
  • 8
  • Why you use 2 Scanner instances? – Juan Carlos Mendoza Oct 23 '17 at 19:42
  • You should check if the value is an int or not at the start when you're accepting the value from the user. – Ragxion Oct 23 '17 at 19:44
  • 1
    Possible duplicate of [Java.util.scanner error handling](https://stackoverflow.com/questions/2696063/java-util-scanner-error-handling) – Stavr00 Oct 23 '17 at 19:44
  • Also, more hints at https://stackoverflow.com/questions/2496239/how-do-i-keep-a-scanner-from-throwing-exceptions-when-the-wrong-type-is-entered/2496812#2496812 – Stavr00 Oct 23 '17 at 19:46
  • I think to input the two variables, I just started learning java yesterday I just code there the if, else if, else statements but he add scanner and wanted me to analyze the whole thing. – alkhemet Oct 23 '17 at 19:47

1 Answers1

0

When you use the nextInt method, it will throw an InputMismatchException if the input value is not a number, then you can use a try-catch block and a loop to validate. You can use a helper method to do this and avoid repeating yourself while reading those values:

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

public class Demo {

    public static void main(String[] args) {
        int x = readNumber();
        int y = readNumber();

        int z;
        z = x + y;

        if (z > 10) {
            System.out.println(z + " is greater than 10");
        } else if (z < 9) {
            System.out.println(z + " is less than 10");
        } else {
            System.out.println(z + " is equal to 10");
        }
    }

    private static int readNumber() {
        Scanner scanner = new Scanner(System.in);
        boolean validInput;
        int result = 0;
        do {
            try {
                System.out.print("Insert a number : ");
                result = scanner.nextInt();
                validInput = true;
            } catch (InputMismatchException e) {
                System.out.println("Not a valid number!");
                validInput = false;
                scanner.nextLine(); // to consume the endline character
            }
        } while (!validInput);
        return result;
    }
}

Another alternative would be using the hasNextInt method.

Juan Carlos Mendoza
  • 5,203
  • 7
  • 21
  • 48