I have a problem in a Java Code Lab that reads as this:
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 . The loop terminates when a value less than 0 is read into 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
amountunconditionally tototal, and then checks if it should have terminated before doing that. Try:or:
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 + 0at the very start of the loop.