Java String - See if a string contains only numbers and not letters

Java String - See if a string contains only numbers and not letters

To check if a String contains only numbers and not letters in Java, you can use regular expressions or iterate through the characters in the String. Here are two approaches:

  • Using Regular Expressions:

You can use a regular expression pattern to match a String that consists of only numeric digits. Here's how to do it:

public static boolean containsOnlyNumbers(String input) { return input.matches("[0-9]+"); } 

In this example, the matches("[0-9]+") method checks if the input String contains only numeric digits. The [0-9]+ regular expression pattern matches one or more numeric digits.

  • Using Character Iteration:

You can also iterate through each character in the String and check if each character is a numeric digit. Here's how to do it:

public static boolean containsOnlyNumbers(String input) { for (char c : input.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } 

In this approach, we use a for-each loop to iterate through each character in the String. The Character.isDigit(c) method checks if each character is a numeric digit. If any character is not a digit, we return false. If all characters are digits, we return true.

You can use either of these methods to check if a String contains only numbers and no letters.


More Tags

jtextfield pyarrow angular2-changedetection system-properties control-panel conditional-statements firebaseui set-returning-functions celerybeat signalr-hub

More Java Questions

More Fitness-Health Calculators

More Dog Calculators

More Internet Calculators

More Various Measurements Units Calculators