Java Write Program Prompts User Enter Two Integers Displays Sum Input Incorrect Prompt Use Q37133461

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 Enter first integer 10 Enter second integer INPUT AN INTEGER ONLY, TRY AGAIN Enter second integer 20 The sum of 10 an

Options

OR
OR

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.