本例考察以下Java知识点:
- 正则表达式
关于正则表达式:
https://www.runoob.com/java/java-regular-expressions.html - Character.isDigit方法
public class StringHasNumber {
public static void main(String[] args) {
System.out.println("Please input a string:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
// 方式1:利用isDigit方式判断
// 方式2:利用正则判断
if(isNumeric(str)){
System.out.println("该字符串含有数字!");
}else{
System.out.println("该字符串不包含数字!");
}
}
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile(".*[0-9].*");
return pattern.matcher(str).matches();
}
}
运行调试



