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);
}
# 1 楼答案
在块外声明并在块内分配:
# 2 楼答案
您正在运行变量的范围。只能在创建变量的范围内使用该变量。这是相同的情况,例如,当您在方法内部创建变量时,您无法从另一个方法访问该变量
您有两个选项:要么在同一范围内使用变量(
try
块),要么在该范围外声明变量选项1:相同范围
选项2:在外部声明它