In Java –
Write a program that prompts the user to enter two integers anddisplays their sum. If the input is incorrect, prompt the useragain. This means that you will have a try-catch inside a loop.
Answer
Code:
import java.util.*;
class Assignment
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int first,second;
while(true)
{
try
{
System.out.println(“Enter first integer”);
first = sc.nextInt();
break;
}
catch (InputMismatchException e)
{
System.out.println(“INPUT AN INTEGER ONLY,TRY AGAIN.”);
sc.nextLine();
}
}
while(true)
{
try
{
System.out.println(“Enter second integer”);
second = sc.nextInt();
break;
}
catch (InputMismatchException e)
{
System.out.println(“INPUT AN INTEGER ONLY,TRY AGAIN.”);
sc.nextLine();
}
}
System.out.println(“The sum of “+first+” and “+second+” is”+(first+second));
}
}
Output:
Options