hoshicchi hoshicchi - 2 months ago 17
Java Question

Sum of 10 Random Numbers Using WHILE Loop - Java

For the last five hours I've been struggling with this Java code that uses a While loop to add up 10 user-input numbers. I've gotten my code to work up until it's time to output the sum (which is always wrong; I usually end up getting 55).

Can someone please help me fix this? I feel as if it's a small error, but I can't tell where it is.

Here's my code:

import java.util.Scanner;

public class Loops {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int sum = 0;
int counter = 0;

while (counter < 10) {
System.out.println("Please enter a number: ");
int i = input.nextInt();
counter++;

sum = sum + counter;
counter = counter + 1;
}
System.out.println("The total sum is " + sum);
}
}

Answer

Your code has a couple of mistakes inside the while loop.

Firstly, on this line:

sum = sum + counter;

you're adding counter to the sum each time. The variable that contains the input number is i, you need to be adding this instead.

Secondly, you're incrementing counter twice each time through the loop. This means you'll only really ask the user for five numbers.

Comments