gpt4 book ai didi

java添加程序: two consecutive zeroes would cause the total of all the values input to be printed and the program to be terminated

转载 作者:行者123 更新时间:2023-12-01 11:19:45 24 4
gpt4 key购买 nike

我想让程序在 0-0 的情况下运行。当我输入0时,它会先显示小计0,然后我需要输入另一个0才能显示总计0,但在我的程序中,当我输入0时,它只会显示总计0。(零值会导致要打印的小计并重置为零)

class Adding{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int subtotal = 0;
int total = 0;

while(true){
while(true){
int number = input.nextInt();

if(number == 0)break;
subtotal = subtotal + number;
}
total = total + subtotal;
if(subtotal != 0){
System.out.println("subtotal: " + subtotal);
subtotal = 0;
}else{
System.out.println("total: " + total);
break;
}
}
}
}

最佳答案

发生这种情况是因为您的情况subTotal!=0。当您输入 0 作为第一个输入时,显然您的小计将为 0。因此它将跳过打印 subtotal:0 并直接打印 total:0。因此,请跟踪您已阅读的输入内容或数量。如果 subTotal!=0 或者这是您的第一个输入,则打印 subTotal

所以我添加了 numbersRead 来跟踪您阅读的字符数。 (即使使用简单的 boolean 值也可以做到这一点)。

将代码更改为:

class Adding{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int subtotal = 0;
int total = 0;
int numbersRead=0;
while(true){
while(true){
int number = input.nextInt();
numbersRead++;
if(number == 0)break;
subtotal = subtotal + number;
}
total = total + subtotal;
if(subtotal != 0 || numbersRead == 1){
System.out.println("subtotal: " + subtotal);
subtotal = 0;
}else{
System.out.println("total: " + total);
break;
}
}
}
}

关于java添加程序: two consecutive zeroes would cause the total of all the values input to be printed and the program to be terminated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31389306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com