0

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
  • Testing a program with 20 user inputs is a nightmare. Consider populating an int array with twenty elements, with 20 user inputs, then pass the array into to a getSum(i[]) function. Then you can create test-data without having to enter...in...all...twenty...numbers...every...SINGLE...time... Ugh. Commented Feb 28, 2014 at 18:19

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I really appreciate the help. The while loop looks good otherwise right?
Will do so as soon as the system lets me :)
0

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

1 Comment

Examples are usually helpful.

Your Answer

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