验证字符串是否仅包含数字的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 字符串也包含字符!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下