Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether a String contains a number value in Java [closed]

Tags:

java

How can I write a method to find whether a given string contains a number? The method should return true if the string contains a number and false otherwise.

like image 962
Ganesamoorthy Avatar asked Jun 14 '11 14:06

Ganesamoorthy


People also ask

How do you check if a string ends with a number in Java?

The recommended solution is to use the Character. isDigit(char) method to check if the first character of the string is a digit or not.


1 Answers

if(str.matches(".*\\d.*")){    // contains a number } else{    // does not contain a number } 

Previous suggested solution, which does not work, but brought back because of @Eng.Fouad's request/suggestion.

Not working suggested solution

String strWithNumber = "This string has a 1 number"; String strWithoutNumber = "This string does not have a number";  System.out.println(strWithNumber.contains("\d")); System.out.println(strWithoutNumber.contains("\d")); 

Working solution

String strWithNumber = "This string has a 1 number"; if(strWithNumber.matches(".*\\d.*")){     System.out.println("'"+strWithNumber+"' contains digit"); } else{     System.out.println("'"+strWithNumber+"' does not contain a digit"); }  String strWithoutNumber = "This string does not have a number"; if(strWithoutNumber.matches(".*\\d.*")){     System.out.println("'"+strWithoutNumber+"' contains digit"); } else{     System.out.println("'"+strWithoutNumber+"' does not contain a digit"); } 

Output

'This string has a 1 number' contains digit 'This string does not have a number' does not contain a digit 
like image 79
Shef Avatar answered Sep 21 '22 03:09

Shef