Java - adding value in a while loop

后端 未结 4 1228
栀梦
栀梦 2021-01-27 14:46

this one just is hurting my brain. http://programmingbydoing.com/a/adding-values-in-a-loop.html

Write a program that gets several integers from the user.

4条回答
  •  情话喂你
    2021-01-27 14:57

    Declare the int sum variable outside of the while loop and only have one guess = keyboard.nextInt() inside the loop. Add the user's guess to the sum in the loop as well.

    Then after the loop output the user's sum.

    I.e.:

    int sum;
    while(guess != 0)
    {   
        guess = keyboard.nextInt();
        sum += guess;
    }
    System.out.println("Total: " + sum");
    

    Edit: also remove the guess2 variable, as you will no longer need it.

提交回复
热议问题