0

我正在尝试使用实用程序函数来获取 int 并检查错误的输入是否会导致
NumberFormat 异常,有没有办法为以下函数使用非十进制 Int

//--- Utility function to get int using a dialog.

public static int getInt(String mess) {
    int val;
    while (true) { // loop until we get a valid int
        String s = JOptionPane.showInputDialog(null, mess);
        try {
            val = Integer.parseInt(s);
            break;  // exit loop with valid int
        } catch (NumberFormatException nx) {
            JOptionPane.showMessageDialog(null, "Enter valid integer");
        }
    }
    return val;
}

//end getInt
4

2 回答 2

1

如果我理解你......也许你可以这样做:

public static int getInt(String mess) {
    int val;
    while (true) { // loop until we get a valid int
        String s = JOptionPane.showInputDialog(null, mess);
        try {
            if(mess.match("^\d+$")){   // Check if it's only numbers (no comma, no dot, only numeric characters)
               val = Integer.parseInt(s); // Check if it's in the range for Integer numbers.
               break;  // exit loop with valid int
            } else  {
               JOptionPane.showMessageDialog(null, "Enter valid integer");
            }
        } catch (NumberFormatException nx) {
            JOptionPane.showMessageDialog(null, "Enter valid integer");
        }
    }
    return val;
}
于 2012-07-11T16:30:28.140 回答
0

试试你想要的,一个用于十进制检查器,一个用于非十进制 int

// 对于十进制

 public static Boolean numberValidate(String text) {
    String expression = "^[+-]?(?:\\d+\\.?\\d*|\\d*\\.?\\d+)[\\r\\n]*$";
    CharSequence inputStr = text;
    Pattern pattern = Pattern.compile(expression);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.find()) {
       MatchResult mResult = matcher.toMatchResult();
       String result = mResult.group();
       return true;
    }
    return false;
}

// 非十进制整数

public static Boolean numberValidate(String text) {
    String expression = "[a-zA-Z]";
    CharSequence inputStr = text;
    Pattern pattern = Pattern.compile(expression);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.find()) {
      MatchResult mResult = matcher.toMatchResult();
      String result = mResult.group();
      return true;
    }
    return false;
}
于 2012-07-11T17:11:16.387 回答