【发布时间】:2020-09-24 13:08:54
【问题描述】:
所以我现在在一个 Java 类中,我们应该使用 ArrayIndexOutOfBoundsExceptions 编写一个程序。很简单,对吧?好吧,无论出于何种原因,我都会收到错误消息:
“错误:不兼容的类型:ArrayIndexOutOfBoundsException 无法转换为 Throwable”
import java.util.*; //for exceptions
class ArrayIndexOutOfBoundsException {
public static void main(String[]args){
int[] array = fillArray(); //filling the array with 100 values
int userInput = getInput();
try{
System.out.print("The value of element "+userInput+" is "+array[userInput]);
}
catch (ArrayIndexOutOfBoundsException ex) {
System.out.print("Out of Bounds");
}
}//end main
public static int[] fillArray(){ //function to fill the array
int[] array = new int[100];
for (int i = 0; i<100;i++)
{
array[i] = (int)(Math.random() *100) + 1;
}
return array;
}//end fillArray
public static int getInput(){ //function to make sure the user enters a proper value
System.out.print("Please enter the index value to find the corresponding value at that location: ");
Scanner input = new Scanner(System.in); //for input
int userInput = 0;
try{
userInput = input.nextInt();
}
catch(InputMismatchException ex){
System.out.println("\nNot a valid number\nPlease Try Again");
return getInput();
}
return userInput;
} //end getInput
}//end class
这是我正在运行的代码,错误发生在“catch (ArrayIndexOutOfBoundsException ex) {”处。
但是,如果我将其切换为 IndexOutOfBoundsException,则代码会按预期工作,而我终其一生都无法弄清楚原因。我的意思是,它被应用于一个数组,所以不应该应用 ArrayIndexOutOfBoundsException 吗?至少这就是我试图用谷歌搜索的问题......但显然我还缺少其他东西。
我在 Repl.it 上运行它,我认为这不会有什么不同,但我不知道?
另外,对于格式错误的代码,我深表歉意,无论出于何种原因,当我复制和粘贴它时,它都变得一团糟,所以这是我能够修复它以使其在合理的时间内可读的最好方法。
无论如何,任何帮助/建议/只要为我指明正确的方向,我们都将不胜感激!谢谢!
【问题讨论】:
-
不要调用你的类 ArrayIndexOutOfBoundsException。您正在掩盖 java.lang.ArrayIndexOutOfBoundsException
标签: java indexoutofboundsexception