JCLeal
JCLeal

Reputation: 11

Adding multiple java arrays once

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);
                    }
}

Upvotes: 0

Views: 51

Answers (1)

Manu
Manu

Reputation: 1485

> 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();
}

Upvotes: 3

Related Questions