Exercise
Sum numbers
Objetive
Write a java program to ask the user for an undetermined amount of numbers (until 0 is entered) and display their sum, as follows:
Number? 5
Total = 5
Number? 10
Total = 15
Number? -2
Total = 13
Number? 0
Finished"
Example Code
import java.util.Scanner;
public class Program {
// Main entry point of the program
public static void main(String[] args) {
// Create a scanner to read user input
Scanner scanner = new Scanner(System.in);
int total = 0;
int number;
// Start a loop to repeatedly ask the user for numbers
do {
// Prompt the user for a number
System.out.print("Number? ");
number = scanner.nextInt();
// Add the entered number to the total sum
total += number;
// Display the updated total
System.out.println("Total = " + total);
} while (number != 0); // Continue until the user enters 0
// Display the message indicating the end of the process
System.out.println("Finished");
}
}