在应用程序中稍后使用try catch块中的值赋值?

时间:2014-10-18 16:32:21

标签: java try-catch

所以我尝试在try-catch之后使用我的变量n,但我不能,因为我的编译器抱怨我的n变量'可能没有被初始化'。我怎样才能解决这个问题?这是代码:

public static void main(String[] args) {

    int n;

    boolean validInput = false;
    String scanner;

    while (!validInput) {
        scanner = JOptionPane.showInputDialog("Please insert an integer:");
        try {
            n = Integer.parseInt(scanner);
            validInput = true;
        } catch (NumberFormatException exception) {
            JOptionPane.showMessageDialog(null, "Not an integer!");
            validInput = false;
        }
    }

    System.out.println(n); //I can't use the n even though I give it a value inside my try-catch
}

2 个答案:

答案 0 :(得分:0)

你应该初始化n。

int n = 0;
...

答案 1 :(得分:0)

您只需要事先对其进行初始化:

public static void main(String[] args) {

    int n = 0;

    boolean validInput = false;
    String scanner;

    while (!validInput) {
        scanner = JOptionPane.showInputDialog("Please insert an integer:");
        try {
            n = Integer.parseInt(scanner);
            validInput = true;
        } catch (NumberFormatException exception) {
            JOptionPane.showMessageDialog(null, "Not an integer!");
            validInput = false;
        }
    }

    System.out.println(n); //I can't use the n even though I give it a value inside my try-catch
}

在旁注中,您根本不需要validInput变量。如果您使用continuebreak语句,则您也不需要初始化变量:

public static void main(String[] args) {
    int n;

    String scanner;

    while (true) {
        JOptionPane.showInputDialog("Please insert an integer:");
        try {
            n = Integer.parseInt(scanner);
            break;
        } catch (NumberFormatException exception) {
            JOptionPane.showMessageDialog(null, "Not an integer!");
            continue;
        }
    }

    s.close();

    System.out.println(n);
}