如果你有一个字符串,想要测试它是否包含整数,以便在继续进行其他代码之前进行检查。在Java中,你会使用什么来确定它是否是整数?
如果你有一个字符串,想要测试它是否包含整数,以便在继续进行其他代码之前进行检查。在Java中,你会使用什么来确定它是否是整数?
如果你想确保一个字符串只包含整数并将其转换为整数,我建议使用 try/catch
中的parseInt方法。然而,如果你想检查字符串是否包含数字,则最好使用String.matches与正则表达式:stringVariable.matches("\\d")
"yourStringHere".matches("\\d+")
。这将检查字符串中是否只包含数字。请注意保留HTML标记。String s = "abc123";
for(char c : s.toCharArray()) {
if(Character.isDigit(c)) {
return true;
}
}
return false;
Scanner input = new Scanner(System.in)
String lectura;
int number;
lectura = input.next();
if(lectura.matches("[0-3]")){
number = lectura;
}
用户正则表达式:
Pattern.compile("^\\s*\\d+\\s*$").matcher(myString).find();
将 Integer.parse() 用 try/catch(NumberFormatException) 包装起来即可。
١
识别为数字? - Michael KonietzkaSystem.out.println(Integer.valueOf("١"));
- Michael Konietzka你可以随时使用谷歌的Guava库
String text = "13567";
CharMatcher charMatcher = CharMatcher.DIGIT;
int output = charMatcher.countIn(text);
那应该可以运行:
public static boolean isInteger(String p_str)
{
if (p_str == null)
return false;
else
return p_str.matches("^\\d*$");
}
int number = 0;
try {
number = Integer.parseInt(string);
}
catch(NumberFormatException e) {}