HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Checking if a string parameter contains only digits

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
digitscheckingcontainsstringonlyparameter

Problem

public void setMobile(String mobile) {
      char[] mobileList = mobile.toCharArray();
      boolean isValid = true;
      for(char x : mobileList)
      {
          if(!Character.isDigit(x))
          {
              isValid = false;
          }
      }
      if(isValid)
      {
          this.mobile = mobile;
      }
    }


Is this the best way of doing things? Cheers.

Solution

There is one major flaw that will come back and haunt you with this code. If you enter an invalid number, there is absolutely no indication whatsoever that it was invalid.

If it is not valid, you should do this:

throw new IllegalArgumentException("Invalid mobile number: " + mobile);


Incorporating Heslacher's suggestions I would do this:

public void setMobile(String mobile) {
    if (!containsOnlyDigits(mobile)) {
        throw new IllegalArgumentException("Invalid mobile number: " + mobile);
    }
    this.mobile = mobile;
}


Another edge case that should be handled is the empty string. I assume you don't want to classify that as a valid mobile number? Then handle it also in containsOnlyDigits or handle it in setMobile.

if (mobile.isEmpty()) {
    throw new IllegalArgumentException("Empty string is not a valid mobile number");
}

Code Snippets

throw new IllegalArgumentException("Invalid mobile number: " + mobile);
public void setMobile(String mobile) {
    if (!containsOnlyDigits(mobile)) {
        throw new IllegalArgumentException("Invalid mobile number: " + mobile);
    }
    this.mobile = mobile;
}
if (mobile.isEmpty()) {
    throw new IllegalArgumentException("Empty string is not a valid mobile number");
}

Context

StackExchange Code Review Q#159712, answer score: 15

Revisions (0)

No revisions yet.