Q10

Question 10

Write a program that reads two integer numbers for the variables a and b. If any other character except number (0-9) is entered then the error is caught by NumberFormatException object. After that ex.getMessage() prints the information about the error occurring causes.

Code Insights

Created java_5.java, a new java class file and imported java.util.Scanner package to take user input and try to cast the input to Integer by in-built method Integer.parseInt() and if it fails to do (String input case) it throws the NumberFormatException.

Browse Source Code

Code

/**
 *Solution for Ans. 10
 * @author Jatin Kamboj 8647
 */
import java.util.Scanner;

public class java_5 {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("\nThis program tells" +
                " if the given INPUT is a number" +
                " or not");
        checkInput(sc, "\nEnter First Number: ");
        checkInput(sc, "\nEnter Second Number: ");
    }

    private static void checkInput(Scanner sc, String s) {
        try {
            System.out.print(s);
            String a = sc.nextLine();
            int parsedValue1 = Integer.parseInt(a);
            System.out.println("\nThe INPUT => " +
                    parsedValue1 +
                    " you gave is a Number");
        } catch (NumberFormatException ex) {
            System.out.println("Your INPUT => " +
                    ex.getMessage() +
                    " is not a Number");
        }
    }

}
Download java_5.java

Output

Image output for java_5.java
Live Demo java_5.java

Last updated