Reputation: 449
String[] invalidChars = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
Scanner sc = new Scanner(System.in);
try {
String country = sc.next();
String state = sc.next();
String city = sc.next();
if(country.contains(invalidChars) || state.contains(invalidChars) || city.contains(invalidChars)) {
}
}
catch(Exception e){}
How would I tell an if statement to check if a string contains any number? I tried the array buy I get an error saying that "String[] cannot be converted to CharSequence"? Any ideas please?
Upvotes: 1
Views: 140
Reputation: 1720
You want to use a regex.
yourString.matches(".*\\d.*"); // returns true if the string contains a number
Upvotes: 1
Reputation: 19776
The most straight-forward in your scenario would be to iterate through your invalid characters, one by one.
for (String invalidChar : invalidChars) {
if(country.contains(invalidChar ) || state.contains(invalidChar ) || city.contains(invalidChar )) {
// do something
break;
}
}
A cleaner way would be to use a regular expression checking for a match on [0-9].
Upvotes: 1