[英]I get the Error when i compile my program (Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException)
Hi Everyone i was practicing Java Language. 大家好,我正在练习Java语言。 And i faced this problem.
我遇到了这个问题。 I'm beginner in this language.
我是这种语言的初学者。 i'm studying it, in my collage.
我正在拼贴中研究它。 Here is the question.
这是问题。
"Create A java program that will derive the sum of a number. For example, an input of 5 will produce(1+2+3+4+5=15)" “创建一个Java程序,该程序将得出一个数字的总和。例如,输入5将产生(1 + 2 + 3 + 4 + 5 = 15)”
i know the answer but i was trying to solve it in another way. 我知道答案,但我正尝试以另一种方式解决。
public class Sum11 {
static int i;
static int[] S = new int[5];
static int j;
static int Sum = 0;
Sum11(int i,int S[],int j){
this.S=S;
this.i=i;
this.j=j;
}
public static void main(String[] args){
Scanner s1 = new Scanner(System.in);
for(i=1;i<=5;i++){
System.out.println("Enter FIve Number");
S[i]= s1.nextInt();
}
for(int num : S){
Sum = Sum+num;
}
System.out.println("The Result IS: "+Sum);
}
}
Array indices in java start in 0, so your input loop should be : Java中的数组索引从0开始,因此您的输入循环应为:
System.out.println("Enter Five Numbers");
for(i=0;i<S.length;i++) {
S[i]= s1.nextInt();
}
The problem with the array index S[5]
in an array of 5 elements is one problem. 由5个元素组成的数组中的数组索引
S[5]
的问题是一个问题。 Another problem is that I think you misunderstood the exercise. 另一个问题是,我认为您误解了该练习。
"Create A java program that will derive the sum of a number. For example, an input of 5 will produce(1+2+3+4+5=15)"
“创建一个Java程序,该程序将得出一个数字的总和。例如,输入5将产生(1 + 2 + 3 + 4 + 5 = 15)”
It asks for "the of a number ", not "number s ", and it seems the input is a single number, for example the number 5. 它要求的“ 一些 ”,而不是“编号的 ”,并且它似乎输入是单数,例如数字5。
The solution of that using a loop could be for example: 使用循环的解决方案例如可以是:
int num = scanner.nextInt();
int sum = 0;
for (int i = 1; i <= num; ++i) {
sum += i;
}
There is also a math solution with a simple formula: 还有一个带有简单公式的数学解决方案:
int num = scanner.nextInt();
int sum = num * (num + 1) / 2;
The array S
is initialized as: 数组
S
初始化为:
static int[] S = new int[5];
And then in the main
function you loop from 1 until 5: 然后在
main
函数中,从1循环到5:
for(i=1;i<=5;i++){ System.out.println("Enter FIve Number"); S[i]= s1.nextInt(); }
Attempting to set values at indexes 1, 2, 3, 4, 5. But in Java array's are 0-based, so the indexes in this example should be 0, 1, 2, 3, 4. 尝试在索引1、2、3、4、5处设置值。但是在Java数组中,索引是基于0的,因此本示例中的索引应为0、1、2、3、4。
You were prone to such problems because S
is declared and initialized so far away from where it's actually used. 之所以容易出现此类问题,是因为
S
的声明和初始化距离实际使用位置很远。 And you don't actually need it at all. 而且您实际上根本不需要它。 You could calculate the sum on the fly, without fumbling with an array:
您可以随时计算总和,而无需弄乱数组:
int sum = 0;
for(i=1;i<=5;i++){
System.out.println("Enter FIve Number");
sum += s1.nextInt();
}
Java数组的起始索引为0。您必须执行以下操作:
for(i=0;i<5;i++){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.