每当布尔方法返回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);
}
}
答案 0 :(得分:0)
您输入10个数字,但您的阵列只有9个点。将其更改为
int [] userArray = new int [10];
答案 1 :(得分:0)
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();
}
答案 2 :(得分:0)
您应该声明一个10号数组,因为您接受来自用户的10个值。
int [] userArray = new int [9];
以下是关于数组的好读物:https://www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html
答案 3 :(得分:0)
您尝试将10个数字存储在长度为9的数组中。
使用int[] userArray = new int[10];