java Create a do-while loop that asks the user to enter two numbers. The numbers
ID: 3700146 • Letter: J
Question
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
Explanation / Answer
Java Program:
import java.util.*;
public class Sum
{
public static void main(String[]arg)
{
//Scanner class object to read input from keyboard
Scanner sc=new Scanner(System.in);
//variable declaration
int sum=0; //holds the sum
String Exit = null;
//storing all the integer values in an array list
ArrayList<Integer> al= new ArrayList<Integer>();
//do while loop starts
do
{
//asks the user to enter two numbers.
System.out.print(" Enter two numbers:");
String input=sc.nextLine();
//dividing the input string based on the space
StringTokenizer st=new StringTokenizer(input," ");
//while loop to store the each number in the array list
while(st.hasMoreTokens())
{
//adding each number in the array list
al.add(Integer.parseInt(st.nextToken()));
}
//asking to continue or exit
System.out.print("Do you want another operation:");
Exit = sc.next();
//skips the extra new line
sc.nextLine();
}while( !("No".equalsIgnoreCase(Exit))) ;
//do while loop ends
//iterator to sum the all integers present in the array list
Iterator<Integer> it=al.iterator();
while(it.hasNext())
{
//summing up
sum=sum+it.next();
}
//displays the output
System.out.println("Sum ="+sum);
}
}
Sample Run1:
Enter two numbers:3 15
Do you want another operation:Yes
Enter two numbers:45 56
Do you want another operation:No
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
Sum =466
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.