有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何访问在Try Catch中创建的数组?

我试图在try函数之外访问数组A,但它说找不到符号。如何在try方法之外访问数组A

try {
        String filePath = "//Users/me/Desktop/list.txt";
        int N = 100000;
        int A[] = new int[N];

        Scanner sc = new Scanner(new File(filePath));

        for (int i = 0; i < N; i++)
        {
            A[i] = sc.nextInt();
        }
    } catch (IOException ioe) {
        System.out.println("IOException: " + ioe);
    }

共 (2) 个答案

  1. # 1 楼答案

    在块外声明并在块内分配:

    int A[];
    
    try {
            String filePath = "//Users/me/Desktop/list.txt";
            int N = 100000;
            A = new int[N];
    
            Scanner sc = new Scanner(new File(filePath));
    
            for (int i = 0; i < N; i++)
            {
                A[i] = sc.nextInt();
            }
        } catch (IOException ioe) {
            System.out.println("IOException: " + ioe);
        }
    
  2. # 2 楼答案

    您正在运行变量的范围。只能在创建变量的范围内使用该变量。这是相同的情况,例如,当您在方法内部创建变量时,您无法从另一个方法访问该变量

    您有两个选项:要么在同一范围内使用变量(try块),要么在该范围外声明变量

    选项1:相同范围

    try {
      ...
      int A[] = new int[N];
      ...
      // use A here only
    } catch (IOException ioe) { ... }
    // A is no longer available for use out here
    

    选项2:在外部声明它

    int A[] = new int [N];
    try {
      ...
    } catch( IOException ioe) { ... }
    // use A here
    // but be careful, you may not have initialized it if you threw and caught the exception!