I'm doing the University of Helsinki's Java MOOC and there is an exercise that asks me to create a program that lets you input as much numbers as you want, but when you input a '0' it prints the sum of all the previously input numbers and ends the program. I can't figure out how to 'store' the input numbers for calculating the sum of them when you input a '0'. The program works but inputting '0' prints '0'. This is how my code looks:
public class Application {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number.");
while (true) {
try {
int number = Integer.parseInt(scanner.nextLine());
System.out.println("Input another number.");
if (number == 0) {
System.out.println(number + number);
break;
}
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
}
How can I calculate the sum of all the input numbers?
You can create a counter and make smth like this, you don't need to save all numbers:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
System.out.println("Input a number.");
while (true) {
try {
int number = Integer.parseInt(scanner.nextLine());
sum += number;
System.out.println("Input another number.");
if (number == 0) {
System.out.println(sum);
break;
}
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
}
In line with my comment above:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int number = -1;
while (number != 0) {
try {
System.out.print("Input a number (0 to quit): ");
number = Integer.parseInt(scanner.nextLine());
sum += number;
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
System.out.println("Total:" + sum);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.