Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何访问在Try-Catch中创建的数组?_Java_Arrays_Try Catch_Java.util.scanner - Fatal编程技术网

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

Java 如何访问在Try-Catch中创建的数组?,java,arrays,try-catch,java.util.scanner,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

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

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

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

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

您有两个选项:在try块的同一作用域中使用变量,或者在该作用域之外声明变量

备选案文1:同一范围

选项2:在外部声明


将使用放在try中,或将创建放在try.Google之外以获取变量范围。基本主题,在任何好书或教程中都有描述。在try块之前创建变量N和数组A作为一般的良好实践,您应该另外限制try/catch仅包括可能实际引发捕获异常的代码行。是的,您仍然可以使用数组@lo1ngru。但要小心,它可能没有填充其值。因此,当您访问[idx]时,它可能是默认的int值0,而不是您期望的文件中的值。如果您的文件包含零,这可能会导致一些混乱。
try {
  ...
  int A[] = new int[N];
  ...
  // use A here only
} catch (IOException ioe) { ... }
// A is no longer available for use out here
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!