Java 程序验证字符串是否只包含数字
要验证字符串是否只包含数字,可尝试以下代码。我们在此处使用 Java 中的 matches() 方法来检查字符串中的数字。
示例
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("String has only numbers!");
else
System.out.println("String consist of characters as well!");
}
}输出
Checking for string that has only numbers... String: 978 String has only numbers!
我们来看另一个示例,其中字符串包含数字和字符。
示例
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("String has only numbers!");
else
System.out.println("String consist of characters as well!");
}
}输出
Checking for string that has only numbers... String: s987jyg String consist of characters as well!
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP