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

时间:2017-07-14 19:47:32

标签: java arrays try-catch java.util.scanner

我尝试在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 个答案:

答案 0 :(得分: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!

答案 1 :(得分:0)

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

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