Java 检查 ParseInt 是否为真

Java Check if ParseInt is True

我正在使用 RGB 输入制作颜色转换器,我想在解析时确保输入是整数。如果其中一个 RGB 值不可解析,则它应该清除该字段但保留已解析的字段。我的代码有效,但我必须使用 3 个 try/catch 语句,但我想将其减少为一个。如果可能,我将如何合并所有这三个?

我假设您在单击 JButton 后收集了所有这些值?好吧,与其这样做,为什么不在客户端完成写入 TextFields 时存储值,然后在该特定字段上使用 parseInt?

field.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) { }

            @Override
            public void focusLost(FocusEvent e) {
                // parse and store int here
            }
        });

How would I merge all these three if possible?

将通用代码移至辅助方法。我也添加了值范围检查。

private static int getChannelValue(JTextField field) {
    String error;
    try {
        int value = Integer.parseInt(field.getText());
        if (value >= 0 && value <= 255)
            return value;
        error = "Out of range";
    } catch (NumberFormatException f) {
        error = "Not an integer number";
    }
    JOptionPane.showMessageDialog(null, "No. " + error);
    field.setText("");
    return -1; // invalid
}
int r = getChannelValue(codeR);
int g = getChannelValue(codeG);
int b = getChannelValue(codeB);
if (r != -1 && g != -1 && b != -1)
    centreName.setForeground(new Color(r, g, b));

因为 Color only accepts integers 0-255, you could instead use a regex

inputString.matches("[12]?\d?\d")

正则表达式的第一个数字接受 1/2/nothing,第二个数字接受数字或不接受任何数字,并且需要第三个数字

这适用于 0-255,但也接受 05、00 和 260 之类的数字(但不接受 005,除非你 [012]),但 Integer.parseInt() 会计算出来

您可能还想排除像 260 这样的值,它包含在:

inputString.matches("1?[0-9]{1,2}|2[0-4][0-9]|25[0-5]")) 将排除 260 之类的值,但不排除 05 或 00