验证字符串是否仅包含数字的Java程序
要验证字符串是否只有数字,您可以尝试以下代码。我们matches()在这里使用Java中的方法检查字符串中的数字。
示例
public class Demo {
public static void main(String []args) {
String str = "978";
System.out.println("Checking for string that has only numbers...");
System.out.println("String: "+str);
if(str.matches("[0-9]+") && str.length() > 2)
System.out.println("字符串只有数字!");
else
System.out.println("字符串也包含字符!");
}
}输出结果
Checking for string that has only numbers... String: 978 字符串只有数字!
让我们看另一个示例,其中我们的字符串既包含数字又包含字符。
示例
public class Demo {
public static void main(String []args) {
String str = "s987jyg";
System.out.println("Checking for string that has only numbers...");
System.out.println("String: "+str);
if(str.matches("[0-9]+") && str.length() > 2)
System.out.println("字符串只有数字!");
else
System.out.println("字符串也包含字符!");
}
}输出结果
Checking for string that has only numbers... String: s987jyg 字符串也包含字符!
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短