验证String是否为整数(numberFormatException)

时间:2014-08-03 21:41:31

标签: java string integer numberformatexception

我试图编写一段代码来测试字符串是否包含整数。我知道try catch解决方案,但是如果从其他类调用该方法,我已经读过它会变坏。我读过的是该方法将显示错误,但调用它的类的主要部分仍将继续运行。 因此,我试图手动完成。我的问题是我能够评估字符串不为空并且字符串中的所有字符都是数字,但我找不到一种方法来验证数字是否太大而无法整数排序。重点是,我在stackoverflow上发现了许多类似的主题,但没有尝试catch就没有人解决这个问题。 这是我的方法。

// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
    int number_of_digits = 0;
    if (str_input.isEmpty()) {
        JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }
    for (char c : str_input.toCharArray()){
        if(Character.isDigit(c)){
            number_of_digits++;
        }
    }
    if (number_of_digits == str_input.length()){
        return true;
    }
    else {
        JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }
}

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

我认为最好的方法就是Leo在评论中所指出的。

public static boolean isInteger(final String strInput) {
    boolean ret = true;
    try {
        Integer.parseInt(strInput);
    } catch (final NumberFormatException e) {
        ret = false;
    }
    return ret;
}

另外,我建议你将GUI部分与检查方法分开,让调用者决定在假的情况下该做什么(例如,在某些情况下,你可能要检查它是否是一个整数,但是不要这样做。 t显示对话框)。

答案 1 :(得分:0)

您可以修改方法以确保数字符合int。

可以通过解析输入,并检查int数的范围来完成。

// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
    int number_of_digits = 0;
    if (str_input.isEmpty()) {
        JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }
    for (char c : str_input.toCharArray()){
        if(Character.isDigit(c)){
            number_of_digits++;
        }
    }
    if (number_of_digits == str_input.length()){
        if (str_input.length > 15) // arbitrary length that is too long for int, but not too long for long
            return false;
        long number = Long.parseLong(str_input);
        if (number > Integer.MAX_VALUE || number < Integer.MIN_VALUE)
           return false;
        else
           return true;
    }
    else {
        JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }
}
顺便说一句,如果你允许负输入,你应该改变你的支票以允许&#39; - &#39;作为第一个角色。

那就是说,我同意所有的评论,说你最好只调用Integer.parseInt()并捕获异常。

答案 2 :(得分:0)

如何使用正则表达式

 -?\\d+(\\.\\d+)? which accept negative and decimal numbers 

来源:http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

 public static boolean isNumeric(String str) {
        return str.matches("-?\\d+(\\.\\d+)?");  
    }