user412308 user412308 - 1 month ago 7
Java Question

Enter 10 values and summing up all the values in a Java Array

I am just starting out with arrays and can't figure out why my code is wrong. It should let the user enter 10 values and then display the sum.

Here is my code:

//This program let the user enter 10 values and sums them up

import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = input.nextInt();

System.out.println("The values are " + myArray[i]);

for (i = 0; i < myArray.length; i++) {

int sum = 0;
sum += myArray[i];

System.out.println("The sum of the values is:" + sum);

}
}

}
}


Thank you for your support

Answer

Your problem comes from your loops (they should be one after the other), and how you initialize your variable sum (it should be initialized outside the loop).

Your code should rather be something like this:

Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
for (int i = 0; i < myArray.length; i++) {
    myArray[i] = input.nextInt();
    System.out.println("The values are " + myArray[i]);
}
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
    sum += myArray[i];
}
System.out.println("The sum of the values is:" + sum);

Or with only one loop

Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
    myArray[i] = input.nextInt();
    System.out.println("The values are " + myArray[i]);
    sum += myArray[i];
}
System.out.println("The sum of the values is:" + sum);