如何检查字符串是否为数字? [英] How to check if a string is numeric?
问题描述
我有一个gpa程序,它适用于 equalsIgnoreCase()
方法,它比较两个字符串,字母a到用户输入,检查它们是否放a与否。但是现在我想添加一个异常,并在输入数字时执行错误消息。我希望程序意识到整数输入与字符串不同并给出错误消息。我可以使用哪些方法将类型 String 变量与 int 类型的输入进行比较,并抛出异常?
I have a gpa program, and it works with the equalsIgnoreCase()
method which compares two strings, the letter "a" to the user input, which checks if they put "a" or not. But now I want to add an exception with an error message that executes when a number is the input. I want the program to realize that the integer input is not the same as string and give an error message. Which methods can I use to compare a type String variable to input of type int, and throw exception?
推荐答案
http:/ /www.coderanch.com/t/405258/java/java/String-IsNumeric
还有一个是
public boolean isNumeric(String s) {
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
可能有点矫枉过正但是 Apache Commons NumberUtils 似乎也有一些助手。
Might be overkill but Apache Commons NumberUtils seems to have some helpers as well.
这篇关于如何检查字符串是否为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!