I have gone through several post and could not find why my code is not working ok.
I have to ask the user to input a string through console with the following format.
[CapitalLeter][Number]
Where the letter must be A,B,C,D,E or F, and the number between 1 and 6.
This is my code.
while ((x.length() != 2) || (x.charAt(0)>='F' && x.charAt(0)<='A') || (Character.getNumericValue(x.charAt(1))>=6 && Character.getNumericValue(x.charAt(1))<=1))
{
System.out.println(msg);
x = (new Scanner(System.in)).nextLine();
}
If I give it for example 3F it will accept it, and its wrong.
Can you help me?
Thanks
since OP answered himself I'll just copy-paste a commend made by @lospejos, which I think is a way better solution than the one proposed by OP (just for future generations sake)
if (matchesFormat(input)) {
/* ok */
} else {
/* not ok */
}
with a helper method
boolean matchesFormat(String input) {
return input.matches("[A-F][1-6]");
}
I was using && when I should be using ||, fixed.
Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.