练习是将所有用户输入的总和相加。
我似乎无法弄清楚如何写sum =所有“ read”的值。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
System.out.println("Enter numbers:");
while (true) {
int read = Integer.parseInt(input.nextLine());
if (read == 0) {
break;
}
read =
System.out.println("Sum now: " + sum);
}
System.out.println("Sum in the end: " + sum);
}
感谢所有帮助。
答案 0 :(得分:1)
这应该通过以下方式实现:
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter numbers:");
try (Scanner input = new Scanner(System.in)) {
while (true) {
int read = Integer.parseInt(input.nextLine());
if (read == 0) {
break;
}
sum += read;
System.out.println("Sum now: " + sum);
}
}
System.out.println("Sum in the end: " + sum);
}
答案 1 :(得分:0)
sum = sum + read
或
sum += read
答案 2 :(得分:0)
public static void main(String[] args) {
int sum = 0;
try (Scanner input = new Scanner(System.in)) {
System.out.println("Enter numbers:");
while (sum >= 0) {
int read = input.nextInt();
sum +=read;
if (read == 0) {
break;
}
System.out.println("Sum now: " + sum);
}
} catch (Exception e) {
System.out.println("Please Enter numbers only");
}
System.out.println("Sum in the end: " + sum);
}