问题
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