使用 try catch 语句检查用户的输入是否为整数

Checking if a user's entry is an integer using try catch statements

try {
        Character.isDigit(Integer.parseInt(txtWeight.getText()));

    } catch (java.lang.NumberFormatException ex) {
        JOptionPane.showMessageDialog(null, "Enter a number");
        pnlStart.setSelectedIndex(2);

    }

txtWeight 是一个 JTextField,用户可以在其中输入自己的值。我需要使用 try catch 检查用户输入的内容是否为整数,以便程序在输入时不会崩溃。

更新:

boolean s = false;
    while (s == false) {
        try {
            Integer.parseInt(txtWeight.getText());
        s = false;
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(null, "Enter a number!");
            s =true;    
        }

    }

我假设你的代码不起作用?

我的方法是创建一个布尔方法和 return true 或 false

boolean checkIfNumber(String s) {
    try {
        Integer.parseInt(s);
    } catch (NumberFormatException ex) {
        JOptionPane.showMessageDialog(null, "Enter a number!");
        return false;
    }
    return true;
}

编辑:

在这种情况下我会做的是,用调用 boolean 方法的 if 语句包围您正在执行的任何代码:

if (checkIfNumber(txtWeight.getText())) {
     //do your code here
} else {
     //do something else if necessary if the return is false
}