【问题标题】:Try...catch block doesn't define variableTry...catch 块没有定义变量
【发布时间】:2012-06-28 11:24:15
【问题描述】:

我有一个程序,它从 args[] 数组中获取一个参数,在 main 方法中定义,但在未定义的情况下有一个备份,以 try...catch 块的形式,它,如果抛出ArrayIndexOutOfBounds 异常,则改为使用称为getInt 的方法来提示用户输入变量。但是,由于某种原因,当我尝试使用该变量时,我的编译器说它找不到它。我有以下代码:

try {
    int limit = Integer.parseInt(args[0]);
}
catch(ArrayIndexOutOfBoundsException e) {
    int limit = getInt("Limit? ");
}
int[] p = getPrimes(limit);

getPrimes 是我拥有的另一种方法,它返回从 2 到指定数字的素数数组(使用阿特金筛)。无论如何,当我写int[] p = getPrimes(limit); 并尝试编译时,它说“限制”变量没有定义。请帮忙!

【问题讨论】:

    标签: java try-catch


    【解决方案1】:

    你应该在块外声明它:

    int limit;
    try {
        limit = Integer.parseInt(stuff[0]);
    }
    catch(ArrayIndexOutOfBoundsException e) {
        limit = getInt("Limit? ");
    }
    int[] p = getPrimes(limit);
    

    【讨论】:

      【解决方案2】:

      在catch块外声明limit,目前在catch块catch{}范围内

      【讨论】:

        【解决方案3】:
        int limit;
        try {
            limit = Integer.parseInt(stuff[0]);
        }
        catch(ArrayIndexOutOfBoundsException e) {
            limit = getInt("Limit? ");
        }
        int[] p = getPrimes(limit);
        

        在您的程序中,您创建了 2 个局部限制变量,一个在 try 块中,另一个在 catch 块中。

        在try块外声明

        【讨论】:

          【解决方案4】:

          在 try/catch 块之外定义限制变量,您无法访问外部 try 块中定义的变量。如果您在 try 块之外调用它,您还必须初始化它,就像您在此处的情况一样。

          【讨论】:

            猜你喜欢
            • 2011-06-01
            • 2013-07-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-09-30
            • 1970-01-01
            • 2012-03-06
            • 1970-01-01
            相关资源
            最近更新 更多