In: Computer Science
Write a Java program (name it InputSum) that prompts the user to enter positive integer numbers using a sentinel while loop. The program should accept integer inputs until the user enters the value -1 (negative one is the sentinel value that stops the while loop). After the user enters -1, the program should display the entered numbers followed by their sum as shown below. Notice that -1 is not part of the output. The program should ignore any other negative input and should continue to run.
Hint: to remember/save the entered (good) positive values, you can concatenate them into a string (separated by comas) that you can output later on.
The following are sample runs showing the input prompt and the outputs: (Notice the user may enter one value per line. DO NOT read inputs as String type)
Enter positive integers (-1 to quit): 10 -5 2 -1
Entered Numbers: 10, 2
The Sum: 12
Enter positive integers (-1 to quit): 1 2 3 4 5 6 -1
Entered Numbers: 1, 2, 3, 4, 5, 6
The Sum: 21
Enter positive integers (-1 to quit): 1 1 -7 1 1 -9 100 -1
Entered Numbers: 1, 1, 1, 1, 100
The Sum: 104
Make sure the program validates each entered number before processing it as the user may enter negative numbers (other than the sentinel value -1).
Design your program such that it allows the user to re-run the program with a different set of inputs in the same run.
Document your code, and organize and space out your outputs as shown above.
Code:
import java.util.Scanner;
class InputSum{
public static void main(String args[]){
Scanner s=new
Scanner(System.in);
String str="";
int r=1,tot=0,x;
do{
tot=0;
System.out.print("Enter positive integers(-1 to quit):");
while(true){
x=s.nextInt();
if(x==-1){
break;
}
else if(x>=1){
tot=tot+x;
str=str+x+",";
}
}
System.out.println("Entered
Numbers:"+str.substring(0,str.length()-1));
System.out.println("The Sum:"+tot);
System.out.print("want to re-run enter 1 otherwise 0:");
r=s.nextInt();
str="";
}while(r!=0);
}
}
Output: