Java中檢查字串是否只包含數字字元
介紹
在本文中,我們將探討如何檢查給定的字串在Java中是否只包含數字或數字和其他字元的混合。我們將透過使用String類及其matches()方法來實現這一點。
問題陳述
給定一個字串,編寫一個Java程式來檢查它是否只包含數字字元。
輸入1
4434
輸出1
String contains only digits!
輸入2
5demo9
輸出2
String contains digits as well as other characters!
在字串中檢查數字字元的步驟
以下是檢查Java中字串是否只包含數字字元的步驟:
- 首先,從一個只包含**數字**的字串開始。
- 然後,我們將使用**matches()方法**來驗證字串是否只包含數字。
- 確保字串的字元數超過兩個。
- 如果兩個條件都滿足,我們將列印一條訊息,指示字串只包含數字。
僅檢查數字
以下是用於檢查數字和其他字元的Java程式:
public class Demo {
public static void main(String []args) {
String str = "4434";
if(str.matches("[0-9]+") && str.length() > 2) {
System.out.println("String contains only digits!");
}
}
}
輸出
String contains only digits!
檢查數字和其他字元
以下是檢查Java中字串是否同時包含數字和非數字字元的步驟:
- 首先,從一個包含**數字**和**非數字字元**的字串開始。
- 然後,我們將再次使用**matches()方法**來檢查字串是否只包含數字。
- 然後驗證字串的字元數是否超過兩個。
- 根據條件,我們將列印字串是否只包含數字或還包括其他字元。
以下是用於檢查數字和其他字元的Java程式:
public class Demo {
public static void main(String []args) {
String str = "5demo9";
System.out.println("String: "+str);
if(str.matches("[0-9]+") && str.length() > 2) {
System.out.println("String contains only digits!");
} else {
System.out.println("String contains digits as well as other characters!");
}
}
}
輸出
String: 5demo9 String contains digits as well as other characters!
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP