Write a simple java program that adds two integers input by user. The program should terminate if any operand is nonnumeric. Before program exit, a message should be displayed that “Input is not valid!”.
Hint: You can use
–NumberFormatException
–InputMismatchException
--ClasscastExcception
import java.util.InputMismatchException;
import java.util.Scanner;
public class Q197435 {
/**
* The start point of the program
* @param args
*/
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
try {
System.out.print("Enter number 1: ");
int number1=input.nextInt();
System.out.print("Enter number 2: ");
int number2=input.nextInt();
int sum=number1+number2;
System.out.println("Sum = "+sum);
}catch (InputMismatchException e) {
System.out.println("Input is not valid!");
}
input.close();
}
}
Comments
Leave a comment