[英]How can I store the scanner input integers in Java so I can print the sum of a list of input integer numbers?
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.我正在做赫尔辛基大学的 Java MOOC,有一个练习要求我创建一个程序,让您输入任意数量的数字,但是当您输入“0”时,它会打印所有先前输入的总和编号并结束程序。 I can't figure out how to 'store' the input numbers for calculating the sum of them when you input a '0'.当您输入“0”时,我无法弄清楚如何“存储”输入数字以计算它们的总和。 The program works but inputting '0' prints '0'.该程序可以运行,但输入“0”会打印“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:您可以创建一个计数器并像这样制作 smth,您不需要保存所有数字:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.