我在第 57 行遇到越界错误。感谢您的帮助。该程序需要 1 个整数并创建具有那么多索引的数组。然后它要求更多的整数来填充它。然后它将所有偶数放入第二个数组中,然后输出。
run:
Enter the ammount of integers you will require.
10
Enter your integers:
1
Enter your integers:
2
Enter your integers:
3
Enter your integers:
4
Enter your integers:
5
Enter your integers:
6
Enter your integers:
7
Enter your integers:
8
Enter your integers:
9
Enter your integers:
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at AllEven.arrcheck2(AllEven.java:57)
at AllEven.main(AllEven.java:24)
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)
代码
import java.util.*;
public class AllEven {
public static void main(String[] args) {
int read;
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the ammount of integers you will require.");
read = kybd.nextInt();
int[] arr1 = new int[read];
int[] arr2;
int count = 0;
arrRead(arr1);
arrcheck(arr1);
arr2 = new int[count];
arrcheck2(arr1, arr2);
mainPrint(arr2);
}
public static int arrcheck(int[] arr1) {
int count = 0;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] % 2 == 0) {
count++;
}
}
return count;
}
public static void arrRead(int[] arr1) {
Scanner kybd = new Scanner(System.in);
for (int i = 0; i < arr1.length; i++) {
System.out.println("Enter your integers: ");
arr1[i] = kybd.nextInt();
}
}
public static void arrcheck2(int[] arr1, int[] arr2) {
int j = 0;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] % 2 == 0) {
arr2[j] = arr1[i];
j++;
}
}
}
public static void mainPrint(int[] arr2) {
for (int i = 0; i < arr2.length; i++) {
System.out.println("Printing Even Numbers.");
System.out.println(arr2[i]);
}
}
}
好的,感谢所有提供帮助的人,但是现在输入整数后,程序就完成了,之后没有显示任何内容。