Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this method always return false?

Tags:

java

I would like to evaluate a phone number using the provided method. The phone number should always have a length of 10. However the following method always seems to return false. Why is that? Thanks.

public static boolean valPhoneNumber(String phonenumber){
    boolean result= true; 

    if (phonenumber.length() > 10 || phonenumber.length() < 10){ 
        result= false;            

    }else                           
            phonenumber.length();
            char a=phonenumber.charAt(0); 
            char b=phonenumber.charAt(1);            
            char d=phonenumber.charAt(3);
            char e=phonenumber.charAt(4);
            char f=phonenumber.charAt(5);

            if (a<2 || a>9){ 
               result = false;
            }else if( b<0 || b>8){ 
                result = false;
            }else if (d<2 || d>9){ 
                result = false;
            }else if (e==1 && f==1){ 
                result = false;
            }                  
    return result;
}
like image 275
Farzan Avatar asked Dec 06 '25 14:12

Farzan


1 Answers

So looking into your ladder which is comparing character to number. In this case the comparison will happen with ASCII value.

You can put single quotes to check the range:

if (a < '2' || a > '9') { 
    result = false;
} else if( b < '0' || b > '8') { 
    result = false;
} else if (d < '2' || d > '9') { 
    result = false;
} else if (e == '1' && f == '1') { 
    result = false;
}

One liner:

result = !((a < '2' || a > '9') || (b < '0' || b > '8') || (d < '2' || d > '9') || (e == '1' && f == '1'));
like image 159
Bilal Siddiqui Avatar answered Dec 09 '25 04:12

Bilal Siddiqui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!