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.