验证字符串是否仅包含数字的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 字符串也包含字符!