Write a java program called InputSum that prompts the user to enter a positive i
ID: 3758658 • Letter: W
Question
Write a java program called InputSum that prompts the user to enter a positive integer number. The program should accept integers until the user enters the value -1 (negative one). After the user enters -1, the program should display the entered numbers followed by their sum as shown below.
You must design the program such that it asks the user if they want to continue with new inputs after each set of entries, ending the program only when they do not respond to the question with "yes".
Notice in the following sample run that -1 is not part of the output that shows the "Entered numbers":
Make sure the program validates each entered number before processing it as the user may enter negative numbers other than the sentential value -1. If it is a negative number that is not -1, then print out, "Invalid Input" and continue to accept numbers. Space out your outputs as shown above.
Explanation / Answer
import java.util.ArrayList;
import java.util.Scanner;
public class InputSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> ae = new ArrayList<>();
System.out.print("Input numbers to add (end with -1): ");
while (true) {
int in = sc.nextInt();
if (in == -1) {
break;
} else if (in < -1) {
System.out.println("Invalid Input");
} else {
ae.add(in);
}
}
System.out.print("Entered numbers: ");
int sum=0;
for (Integer i : ae) {
sum += i;
System.out.print(i+",");
}
System.out.println();
System.out.println("The sum: "+sum);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.