我的代码有问题:
import java.io.*;
import java.util.*;
public class goTooFar {
public static void main(String[] a){
int i =4;
int[] ar = new int[i];
int n = i;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of an array: ");
try {
n = sc.nextInt();
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Now you have gone too far");
}
System.out.println("Enter " + n + " elements of an array: ");
for (i = 0; i <= n; i++) {
try {
ar[i] = sc.nextInt();
} catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println("Now you have gone too far");
}
System.out.println("Output Numbers: ");
for (i = 0; i <= n; i++) {
System.out.println(ar[i]);
}
}
}
}
我有这样的输入:
> Enter the size of an array:
7
> Enter 7 elements of an array:
1 4 2 5 3 9 0 7
但是,事实证明是这样的:
>Output Numbers:
1
0
0
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at goTooFar.main(goTooFar.java:31)
我该怎么做才能解决此问题?有人能帮我吗?非常感谢。 :)
最佳答案
您将数组的长度初始化为4:
int i =4;
int[] ar = new int[i];
因此,当您输入更长的数组长度时,您将获得ArrayIndexOutOfBoundsException。
您需要从用户获取长度后创建数组:
System.out.println("Enter " + n + " elements of an array: ");
ar = new int[n]; // initialize a new array
for(i = 0; i < n; i++){ // n is not a valid index for an array of length n
同时更改另一个循环的范围
for(i = 0; i <= n; i++){
System.out.println(ar[i]);
}
至
for(i = 0; i < n; i++){
System.out.println(ar[i]);
}
关于java - ArayIndexOutOfBoundsException不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31917936/