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