Sum numbers using loop

故事扮演 提交于 2021-02-04 21:33:57

问题


My objective: write an application that uses while loop to get 20 inputs from a user and displays the sum of all those numbers.

I get how to do the while loop but I don't know how to get the sum of all those numbers (because the variable will be the same). Here is what I have so far:

Scanner Numb = new Scanner (System.in); 
int count = 0;
while (count<20) {
    System.out.println("Enter number: ");
    int numb = Numb.nextInt();
    count++;

回答1:


use a common variable to store sum

int sum = 0;
int count = 0;
while (count<20) {
    System.out.println("Enter number: ");
    int numb = Numb.nextInt();
    sum = sum+numb;
    count++;
}
System.out.println("sum is "+sum);



回答2:


you need another variable to add it to that is outside the while loop.



来源:https://stackoverflow.com/questions/22102720/sum-numbers-using-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!