[英]Try…catch block doesn't define variable
I have a program, which takes a parameter from the args[]
array, defined in the main method, but has a backup in case that isn't defined, in the form of a try...catch block, which, if an ArrayIndexOutOfBounds
exception is thrown, instead uses a method called getInt
to prompt the user to enter a variable. 我有一个程序,该程序从
args[]
数组中获取参数,该args[]
是在main方法中定义的,但是有一个备份(如果未定义),其形式为try ... catch块,如果...引发ArrayIndexOutOfBounds
异常,而是使用名为getInt
的方法来提示用户输入变量。 But, for some reason, when I try to use that variable, my compiler says that it cannot find it. 但是,由于某种原因,当我尝试使用该变量时,编译器表示找不到该变量。 I have the following code:
我有以下代码:
try {
int limit = Integer.parseInt(args[0]);
}
catch(ArrayIndexOutOfBoundsException e) {
int limit = getInt("Limit? ");
}
int[] p = getPrimes(limit);
getPrimes
is another method I have, which returns an array of prime numbers starting from 2 and up to a specified number (using the Sieve of Atkin). getPrimes
是我拥有的另一个方法,它返回一个从2到指定数字(使用Atkin筛子)的素数数组。 Anyway, when I write int[] p = getPrimes(limit);
无论如何,当我写
int[] p = getPrimes(limit);
and try compiling, it says that the "limit" variable is not defined. 然后尝试编译,它说未定义“ limit”变量。 Help please!
请帮助!
You should declare it outside the block: 您应该在块外声明它:
int limit;
try {
limit = Integer.parseInt(stuff[0]);
}
catch(ArrayIndexOutOfBoundsException e) {
limit = getInt("Limit? ");
}
int[] p = getPrimes(limit);
在catch块之外声明limit
,当前在catch块catch{}
的范围内
int limit;
try {
limit = Integer.parseInt(stuff[0]);
}
catch(ArrayIndexOutOfBoundsException e) {
limit = getInt("Limit? ");
}
int[] p = getPrimes(limit);
In your program you have created 2 local Limit variable one in try
block and another in catch
block. 在您的程序中,您创建了2个局部Limit变量,一个在
try
块中,另一个在catch
块中。
Declare it outside the try block 在try块外声明它
Define limit variable outside of try/catch block, you do not have access to variables defined inside try block outside. 在try / catch块外部定义限制变量,您无权访问try / catch块外部定义的变量。 You would also have to initialize it if you are calling it outside of try block as in your case here.
如果要在try块之外调用它,则也必须对其进行初始化,如此处的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.