Question

3) Sum. Write a program that prompts the user to read two integers and displays their sum. Your program should prompt the usein java

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program

import java.util.Scanner; //importing Scanner class
public class Main
{
   public static void main(String[] args) {
   Scanner sc=new Scanner(System.in);
   String num1="",num2=""; //declaring two number variables as string
   int sum; //variable to store sum of numbers
   int flag=0;
       System.out.print("Enter first number:");
      
       while(flag==0){
       num1=sc.next();
       try{
   Integer.parseInt(num1); //checking to convert the string into integer
   flag=1;
}catch(NumberFormatException e){ //if it throw an Exception then
   System.out.print("Enter first number correctly:");
   flag=0;
}
       }
       System.out.print("Enter second number:");
      
       flag=0;
       while(flag==0){
       num2=sc.next();
       try{
   Integer.parseInt(num2); //checking to convert the string into integer
   flag=1;
}catch(NumberFormatException e){ //if it throw an Exception then
   System.out.print("Enter second number correctly:");
   flag=0;
}
       }
       sum=Integer.parseInt(num1)+Integer.parseInt(num2); //finding sum
       System.out.println("Sum is "+sum);
      
   }
}

Screenshot of the code

{ 1 import java.util.Scanner; //importing Scanner class 2 public class Main 3 4. public static void main(String[] args) { 5 S

Output

Enter first number:43 Enter second number:13 Sum is 56

Enter first number:ok Enter first number correctly:23 Enter second number:k Enter second number correctly:/; Enter second num

If you find this answer useful , please rate positive , thankyou

Add a comment
Know the answer?
Add Answer to:
in java 3) Sum. Write a program that prompts the user to read two integers and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT