How to check if a s…
 
Notifications
Clear all

How to check if a string contains only digits?

1 Posts
2 Users
0 Likes
590 Views
0
Topic starter

How to check if a string contains only digits?

1 Answer
0
class Test {

  public static void main(String[] args) {
    String str = "129843875";
    boolean containsOnlyDigits = true;

    for (int i = 0; i < str.length(); i++) {
      if (!Character.isDigit(str.charAt(i))) { // in case that a char is NOT a digit, enter to the if code block
        containsOnlyDigits = false;
        break; // break the loop, since we found that this char is not a digit
      }
    }

    if (containsOnlyDigits) {
      System.out.println("String contains only digits!");
    } else {
      System.out.println("String does not contain only digits!");
    }
  }
}

Try the above code.

Share: