0

I am trying to create a simple program that asks you 10 integers and the program will automatically add them all. I always get an error from Java which is this

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 55 at Sum2.main(Sum2.java:29)

How can I add those multiple array values once? I tried using

integerArray[0]+[1].....

But it is still not working, please help.

import java.util.Scanner;


public class Sum2 {

private static Scanner sc;

public static void main(String[] args) {

    int totalsum;
    int[] integerArray = new int[11];

    sc = new Scanner(System.in);

    System.out.println("Please enter your 10 integers : ");

    integerArray[0] = sc.nextInt();
    integerArray[1] = sc.nextInt();
    integerArray[2] = sc.nextInt();
    integerArray[3] = sc.nextInt();
    integerArray[4] = sc.nextInt();
    integerArray[5] = sc.nextInt();
    integerArray[6] = sc.nextInt();
    integerArray[7] = sc.nextInt();
    integerArray[8] = sc.nextInt();
    integerArray[9] = sc.nextInt();
    integerArray[10] = sc.nextInt();

    totalsum = integerArray[0+1+2+3+4+5+6+7+8+9+10];

    System.out.println("The sum of the first 10 integers is: " +totalsum);
                    }
}
1
  • You want integerArray[0] + integerArray[1] + .... Now you're doing the addition for the index (0+1+2...+10 = 55). Commented Jun 24, 2015 at 11:53

1 Answer 1

3
> totalsum = integerArray[0]
    + integerArray[1]
    + integerArray[2]
    + integerArray[3]
    + integerArray[4]
    + integerArray[5]
    + integerArray[6]
    + integerArray[7]
    + integerArray[8]
    + integerArray[9];

Or

totalsum = 0;
for(int i = 0; i < 10; i++) {
    totalsum += integerArray[i];
}

By the way, your array contains 11 Integers, not 10.


EDIT: (reply on your comment)

About making code cleaner, this is a lot better than 10 times the same line:

System.out.println("Please enter your 10 integers : ");
for(int i = 0; i < 10; i++) {
    integerArray[i] = sc.nextInt();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I tried the first method but I forgot to mention how to make it more decent and cleaner, sorry for that.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.