4
/**
 * Set the person's mobile phone number
 */
public void setMobile(String mobile) {
    for (int i = 0; i < mobile.length(); i++) {
if (!Character.isDigit(mobile.charAt(i))) {}
}
this.mobile = mobile;
}

So I basically need to make sure the string only contains digits, and if it contains non-digits for the method just to do nothing. The problem I have is that if there is a random character in a string of numbers i.e. "034343a45645" it will still set the method. Any help is appreciated thanks!

hK-
  • 57
  • 1
  • 4
  • http://stackoverflow.com/questions/10575624/java-string-see-if-a-string-contains-only-numbers-and-not-letters – prasanth Apr 09 '17 at 04:30

3 Answers3

7

You could use String.matches(String regex):

boolean onlyDigits = mobile.matches("[0-9]+");

With a for loop you can just break when a non-digits is found.

boolean onlyDigits = true;
for (int i = 0; i < mobile.length(); i++) {
    if (!Character.isDigit(mobile.charAt(i))) {
        onlyDigits = false;
        break;
   }
}

Instead of breaking out of the loop, you could also just return. As it sounds like you don't want anything else to happen after. Thus eliminating the need for the onlyDigits variable to begin with.

Note that if mobile.length() == 0 then onlyDigits would still be true in relation to the above for loop. So assuming onlyDigits should be false if mobile is an empty string, then you could initialize it as such:

boolean onlyDigits = !mobile.isEmpty()

After checking you can then assign it if onlyDigits is true.

if (onlyDigits)
    this.mobile = mobile;
vallentin
  • 23,478
  • 6
  • 59
  • 81
2

You have two problems:

First: you didn't exit the loop if the if condition is false

Second: why using loop try implement tryParse like this

boolean tryParseInt(String value) {  
     try {  
         Integer.parseInt(value);  
         return true;  
      } catch (NumberFormatException e) {  
         return false;  
      }  
}

if(tryParseInt(mobile)){
  this.mobile = mobile;
}
Fady Saad
  • 1,169
  • 8
  • 13
0

add a boolean letterFound;

then at your for loop

whenever a letter is found use your else statement to set letterFound to true

then immediately stop the loop i=mobile.length() at your else statement

0xDEADBEEF
  • 590
  • 1
  • 5
  • 16