Internet Technologies
1.0.0
1.0.0
  • Introduction
  • Contents
  • Practical List
  • HTML & CSS
    • Q1
    • Q2
    • Q3
    • Q4
    • Q5
  • JAVA Programs
    • Q6
    • Q7
    • Q8
    • Q9
    • Q10
    • Q11
    • Q12
  • JAVASCRIPT
    • Q13
    • Q14
    • Q15
  • JDBC
    • Q16
    • Q17
  • JSP
    • Side Note
    • Q18
    • Q19
    • Q20
    • Q21
    • Q22
    • Q23
  • End
Powered by GitBook
On this page
  • Code
  • Output
  1. JAVA Programs

Q10

Question 10

PreviousQ9NextQ11

Last updated 4 years ago

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.

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");
        }
    }

}

Output

Try or Test The Corresponding Code Here

The above notebook runs on cloud, make sure to run the first cell of the notebook to set-up JDK and JRE on the cloud machine.

Browse Source Code
Google Colaboratory
Live Demo java_5.java
Logo
927B
java_5.java
Download java_5.java
Image output for java_5.java