I want to check whether the entered strings length is between 3 to 8 characters. Previously I used if condition
and it worked. However when I introduced some substring from the string , one of the if statements
doesnt work. Can some one help me to understand why. Thanks.
My codes is
Working Code:
text = et.getText().toString();
l = text.length();
a = text.substring(0, 1);
if (l >=9) tv.setText("Invalid length!!! Please check your code");
if (l <= 2) tv.setText("Invalid length! Please check your code");
And here, the second if statement doesnt
work.
text = et.getText().toString();
l = text.length();
a = text.substring(0, 1);
c = text.substring(1, 2);
d = text.substring(3, 4);
e = text.substring(4);
if (l >=9) tv.setText("Invalid length!!! Please check your code");
if (l <= 2) tv.setText("Invalid length! Please check your code");
The length() method returns the length of a specified string. Note: The length of an empty string is 0.
As you know, the best way to find the length of a string is by using the strlen() function.
To calculate the length of a string in Java, you can use an inbuilt length() method of the Java string class. In Java, strings are objects created using the string class and the length() method is a public member method of this class. So, any variable of type string can access this method using the . (dot) operator.
You will want to ensure that you handle a null string as well as ensuring your string is within the limits you want. consider:
text = et.getText().toString();
if (text == null || text.length() < 3 || text.length > 8) {
tv.setText("Invalid length, should be from 3 to 8 characters. Please check your code");
} else {
a = text.substring(0,1);
b = text.substring(1,2);
c = text.substring(3,4);
if (text.length() > 3) {
d = text.substring(4);
} else {
d = null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With