![](/img/trans.png)
[英]Fixing Exception in thread “main” java.lang.StackOverflowError
[英]fixing Exception in main thread
每当布尔方法返回true时,我的代码中的所有内容似乎都能正常运行。 但是,当尝试测试false时,在用户输入10个数字后,我收到以下错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at FunArrays.main(FunArrays.java:15
我的代码缺少或忽略了什么?
这是我的代码:
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Please enter ten numbers....");
int [] userArray = new int [9];
for(int b = 0; b < 10 ; b++){
userArray [b] = input.nextInt();
}
boolean lucky = isLucky(userArray);
if (lucky){
sum(userArray);
} else
sumOfEvens(userArray);
}
public static boolean isLucky(int [] numbers){
for (int i = 0; i <= numbers.length; i++){
if (numbers[i]== 7 || numbers[i] == 13 || numbers[i] == 18){
return true;
}
}
return false;
}
public static void sum(int [] numbers){
int sum = 0;
for (int x = 0; x <= numbers.length -1; x++){
sum += numbers[x];
}
System.out.println(sum);
}
public static void sumOfEvens(int [] numbers){
int evens = 0;
for (int y = 0; y <= numbers.length -1; y++){
if (numbers[y] % 2 == 0){
evens += numbers[y];
}
}
System.out.println(evens);
}
}
您正在输入10个数字,但您的数组只有9个点。 更改为
int [] userArray = new int [10];
int [] userArray = new int [9];
for(int b = 0; b < 10 ; b++){
userArray [b] = input.nextInt();
}
您的数组大小为9(从索引0到索引8),循环增量b从0到9(10种情况)。在这种情况下,循环中b应当小于9。
因此,您可以用以下代码替换:
int maxInput = 9;
int [] userArray = new int [maxInput];
for(int b = 0; b < maxInput ; b++){
userArray [b] = input.nextInt();
}
您应该声明一个大小为10的数组,因为您要接受用户的10个值。
int [] userArray = new int [9];
这是有关Arrays的好读物: https : //www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html
您正在尝试将10个数字存储在长度为9的数组中。
使用int[] userArray = new int[10];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.