简体   繁体   English

While循环读取非负值,并在读取小于0的值时终止

[英]While Loop that reads non-negative values and terminates when a value less than 0 is read

I have a problem in a Java Code Lab that reads as this: 我在Java代码实验室中遇到一个问题,内容如下:

Give that two int variables, total and amount have been declared, write a loop that reads non-negative values into amount and adds them into total . 给出已经声明了两个int变量total和total的代码,编写一个循环,将非负值读入value并将其添加到total中。 The loop terminates when a value less than 0 is read into amount . 当将小于0的值读入amount时,循环终止。

My output either says that I am including a negative value in my sum OR I seem to be stopping at zero, depending on how I code the statement. 我的输出要么表明我在总和中包括一个负值,要么我似乎停止为零,这取决于我对语句的编码方式。

My loop is as follows: 我的循环如下:

total = 0;
amount = 0;
while( amount > -1 )
{

amount = TC.getNum();

total = total + amount;
}

This particular one says I seem to be stopping at zero. 这个特别的人说我似乎停在零。

Your code adds amount unconditionally to total , and then checks if it should have terminated before doing that. 您的代码无条件地total amount添加到total ,然后在执行此操作之前检查它是否应该终止。 Try: 尝试:

total = 0;
amount = 0;
do {
    total = total + amount;
    amount = TC.getNum();
} while ( amount > -1 );

or: 要么:

total = 0;
amount = 0;
while(true) {
    amount = TC.getNum();
    if (amount < 0)
        break;
    total = total + amount;
}

I'm not sure myself which I like better. 我不确定自己更喜欢哪个。

Edit: I think I like the second version better. 编辑:我想我更喜欢第二个版本。 It reads more naturally, and the first one may confuse due to a superfluous (and potentially error-prone) total = total + 0 at the very start of the loop. 它更自然地读取,并且第一个可能会由于在循环的最开始处出现多余的(可能容易出错) total = total + 0而感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM