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!

更新於: 26-Jun-2020

2K+ 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.