Reputation:
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++;
Upvotes: 0
Views: 1497
Reputation: 5637
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);
Upvotes: 3
Reputation: 2358
you need another variable to add it to that is outside the while loop.
Upvotes: 0