【发布时间】:2015-06-24 11:52:28
【问题描述】:
我正在尝试创建一个简单的程序,它会询问您 10 个整数,然后程序会自动将它们全部添加。我总是从 Java 中得到一个错误,就是这个
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 55 在 Sum2.main(Sum2.java:29)
如何一次添加多个数组值? 我尝试使用
整数数组[0]+[1].....
但还是不行,请帮忙。
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);
}
}
【问题讨论】:
-
你想要
integerArray[0] + integerArray[1] + ...。现在您正在为索引 (0+1+2...+10 = 55) 进行加法。