Q:

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:
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. 

A:

Your code adds amount unconditionally to total, and then checks if it should have terminated before doing that. 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.

