0
import java.util.*;

public class ArrayIndexOutOfBoundsException {
    public static void main(String[] args) {
        int[] array = new int[100];  

//创建一个有 100 个存储空间的数组 for(int i = 0; i < array.length; i++) { //for 循环在数组的每个索引中存储随机整数 array[i] = (int) (Math.random ()*100); }

        Scanner input = new Scanner(System.in);
        System.out.println("Enter the index of the array: "); 

//提示用户输入索引来查找

        try {
            int index = input.nextInt(); //declaring index variable to take on inputed value
            System.out.println("The integer at index "+index+" is: "+array[index]); //printing the integer at the specified index
        
        }
        catch (ArrayIndexOutOfBoundsException ex) { //if user enters index value outside of 0-99, exception message will print
            System.out.println("Out of bounds.");
        }

        
    } 
        
}
4

2 回答 2

0

当您的代码被编译为字节码时,编译器必须发现所有类并将所有名称扩展到它们的 FQDN - 包 + 类名

在您的情况下,编译程序时,主类名称是 ArrayIndexOutOfBoundsException - 因此编译器将 ArrayIndexOutOfBoundsException 映射到您自己的类。

当编译器赶上线路时,它会采用 ArrayIndexOutOfBoundsException 并尝试首先在地图中找到它 - 它就在那里。所以编译器开始检查正确性,特别是类必须在 Throwable 层次结构中。由于它不在可抛出的层次结构中(您的类隐式扩展了 Object),因此编译器会返回错误。

您可以使用两种方法修复它:

  1. 重命名主类以避免歧义
  2. 在 catch 你可以指定类的全名:java.lang.ArrayIndexOutOfBoundsException

第二个选项有助于解决一个通用问题:如果两个类具有相同的名称,但必须在相同的范围内使用怎么办。

于 2022-03-03T19:59:12.500 回答
0

ArrayIndexOutOfBoundsException 异常类型包含在 java/lang 包中。因此,您必须在 catch 子句中导入它或使用全名:

catch (java.lang.ArrayIndexOutOfBoundsException ex)

在您的情况下,导入不起作用,因为您的类也称为 ArrayIndexOutOfBoundsException,因此您需要在 catch 子句中使用全名。

作为最后的建议,我建议您将类重命名为一个好的实践,因为它现在可能会导致混淆并使代码难以阅读。

于 2022-03-03T20:22:00.183 回答