Answer to Question #197435 in Java | JSP | JSF for Syed kaif ali

Question #197435

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



1
Expert's answer
2021-05-23T12:18:15-0400
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();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS