catch中创建的数组?

bz4sfanl  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(335)

我试图在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);
    }
8gsdolmq

8gsdolmq1#

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

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);
    }
1u4esq0p

1u4esq0p2#

您正在运行变量的作用域。只能在创建变量的范围内使用该变量。同样的情况,例如,当你在一个方法中创建一个变量时——你不能从另一个方法中访问这个变量。
您有两个选项:要么在同一范围内使用变量(即 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!

相关问题