/**
* Given a String as input, return true if the String represents a valid
* binary value (i.e. contains only the digits 1 and 0). Returns false if
* the String does not represent a binary value.
*
* @param value
* A String value that may contain a binary value
* @return true if the String value contains a binary value, false otherwise
*/
无论我做什么,都只会返回false。我是编程新手,很想了解逻辑如何运行。感谢您提供的所有帮助。
public static boolean validBinary(String value) {
int b = Integer.parseInt(value);
int binCount = 0;
for(int i = 0; i < value.length(); i++) {
int tempB = value.charAt(i);
if(tempB % 10 == 0 || tempB % 10 == 1) {
binCount = binCount + 1;
}
else {
binCount = -1;
break;
}
}
if (binCount > 0) {
return true;
}
else {
return false;
}
}
我认为可以用更简单的方法实现:
public static boolean validBinary(String value):
return value.chars().filter(ch -> ch != '0' || ch != '1').count() == 0
最简单的方法是遍历所有字符,并确定作为字符的字符串是否包含全0和1。
boolean binary = value.chars().allMatch(character -> character == 0 || character == 1);