185k views
4 votes
Java

Create a do-while loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The loop should ask the user whether he or she wishes to perform the operation again. If so, the loop should repeat; otherwise it should terminate
Sample Run1
Enter two numbers: 3 15
Do you want another operation: Yes
Enter two numbers: 45 56
Do you want another operation: No
Output1: Sum = 119
Sample Run2
Enter two numbers: 33 150
Do you want another operation: Yes
Enter two numbers: -56 56
Do you want another operation: Yes
Enter two numbers: 58 15
Do you want another operation: Yes
Enter two numbers: 123 87
Do you want another operation: No
Output2: Sum = 466

1 Answer

6 votes

Answer:

import java.util.Scanner;

public class num3 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.print("Enter two numbers: ");

int num1 = in.nextInt();

int num2 = in.nextInt();

int sum = num1+num2;

System.out.print("Do you want another operation: ");

String ans = in.next();

while(ans.equalsIgnoreCase("yes")){

System.out.print("Enter two numbers:");

num1= in.nextInt();

num2 = in.nextInt();

System.out.println("Do you want another operation: ");

ans = in.next();

sum = sum+(num1+num2);

}

System.out.println("sum = "+sum);

}

}

Step-by-step explanation:

In the program written in Java Programming language,

The scanner class is used to prompt and receive two numbers from the user which are stored as num1 and num2. Another variable sum is created to hold the sum of this numbers

Then the user is prompted to answer yes or no using Java's equal.IgnoreCase() method.

If the user enters yes, he/she is allowed to entered two more numbers that are countinually added to sum

If the user eventually enters a string that is not equal to yes. The loop terminates and the accumulated value of sum is printed.

User SSF
by
5.2k points