Reputation: 1
I am coding in java a boolean method to validate user input is correct. It is correct if the first thing typed is a letter A-D and the second thing typed is 1-4 (e.g. B3). When I set up my if statements I am getting an error next to them that say "The operator == is undefined for the argument type(s) char, boolean". I cannot figure out what I am doing wrong. Here is the snippet of code.
public static boolean isValid(String s) {
if (!isUpperCase(s)) {
s = s.toUpperCase();
}
if (s.length() < 2) {
if (s.charAt(0) == 'A' <= 'D') { // here is the first place I'm getting the error
if (s.charAt(1) >= 1 <= 4) { // here is the second place I'm getting a similar error
return true;
}
}
}
return false;
}
Please excuse my ignorance as I am a novice coder and do not know all the terminology
Upvotes: 0
Views: 447
Reputation: 210
Even though there are two offered solutions right now, I didn't see any of them explaining why there's a problem. Thus I want to explain: The problem is the way you write your if statements. When you say if (s.charAt(0) == 'A' <= 'D')
, the if feels like it is comparing a char and a boolean. Because 'A' <= 'D' is perceived as a true boolean statement.
With that said, you can use &&
and check if your char is char >= A && char <= D
Upvotes: 0
Reputation: 51445
You have to specify two variables or constants in an if
statement. You can connect pairs with logical operators like AND (&&) or OR (||).
You don't need to test if the String is upper case. Converting it to upper case won't change anything if the letter is already in upper case.
Here's your method.
public static boolean isValid(String s) {
if (s.length() < 2) {
s = s.toUpperCase();
if (s.charAt(0) >= 'A' && s.charAt(0) <= 'D') {
if (s.charAt(1) >= '1' && s.charAt(1) <= '4') {
return true;
}
}
}
return false;
}
Upvotes: 0
Reputation: 19545
It is possible to use String method matches
which uses a regular expression:
private static boolean isValid(String s) {
return null != s && s.matches("(?i)[A-D][1-4]");
}
where
(?i)
- enable case-insensitive matching
[A-D][1-4]
- a single letter in range [A..D]
followed by a single digit in range [1..4]
Upvotes: 1