I’m having an issue comparing a character in Java. I’m trying to find a valid binary number, so I’m passing a string with the binary digits into a function and making sure they’re either 0’s or 1’s. I loop through and check each character in the string, however, my function is telling me that it’s bad (even when I know I’ve given it a proper binary number).
Here is the function:
public boolean isValidBinary(String s) {
//First we get the string length
int strLen = s.length();
//Now we loop through each character of the string
for(int x = 0; x < strLen; x++) {
//Assign the character to a variable each loopthrough
char c = s.charAt(x);
//Check if it's either a 0 or a 1
if(c != '0' || c != '1') {
return false;
}
}
//This is reached when all char's have been evaluated as 0 or 1
return true;
}
I have stared at this problem for quite some time and have been unable to figure it out, so any help would be appreciated.
That’s a logical error. You meant
&&instead of||.You could use a regular expression for this anyway: