0

I am having trouble with this simple loop for a uni lab. It wont stop looping until I put in a number over a thousand. I can't see where I have gone wrong on such a simple loop.

I have meant to have written a simple method that will loop through adding numbers until the number is greater than 100 and then once it has reached 100 or greater it will output the total.

public void adder2(){
    int sum = 0;
    int number = 0;
    while(number < 100){
        sum = sum + number;
        number = getNumber();
    }
    System.out.println("The result is " + sum);
}
2
  • 7
    Im sure the error is inside getNumber(). Can you please post that function? Commented Nov 19, 2011 at 23:26
  • 2
    what is getNumber() returning? Commented Nov 19, 2011 at 23:26

1 Answer 1

1

Try this: while (sum < 100 && number < 100) { ...code as above... }

Sign up to request clarification or add additional context in comments.

10 Comments

you are correct. The reason I was going by the number variable was because the previous example was to add numbers until the user entered the number -99.
I think that you got downvoted because without more information your response is just a wild guess which, in worst case, might actually hide the real problem instead of fixing it.
if that's true case (btw I didn't downvote) than @jamcoupe cannot explain well his tasks. "method that will loop through adding numbers until the number is greater than 100" does not mean that the SUM will also have to be < 100.
@kol Do you have some magical knowledge of getNumber() that the rest of us don't? :D
@FailedDev Yeah, I got all these magical feelings and knowledge :) Anyway, it was dead easy: he didn't check whether the sum variable reached 100. I always check the simplest possible bug first...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.