/**
* 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) {
删除以下内容,因为它没有被使用。
int b = Integer.parseInt(value);
初始化binCount
并启动循环。
int binCount = 0;
for(int i = 0; i < value.length(); i++) {
int tempB = value.charAt(i);
这就是问题开始的地方。即使tempB
被声明为一个,int
它仍然具有 ASCII 字符的值。因此,“0”到“9”实际上是 48 到 57(包括 48 到 57)。因此,与其转换为整数,不如将它们作为字符进行比较。在这种情况下,您可以忘记 % 运算符。所以新的 if 语句应该是:
if (tempB == '0' || tempB == '1') {
代替
if(tempB % 10 == 0 || tempB % 10 == 1) {
保留其余代码,程序应该可以正常工作。
binCount = binCount + 1;
}
else {
binCount = -1;
break;
}
}
if (binCount > 0) {
return true;
}
else {
return false;
}
}
练习的重点是验证数字是否为二进制。所以你不需要任何簿记,比如bincount
这样做。一旦您的测试0
或1
失败,只需返回false
。无需进一步处理。但是如果你完成了整个字符串的检查并且没有通过测试,那么所有的字符都必须是 0 或 1。所以返回true
。那看起来像这样。
for(int i = 0; i < value.length(); i++) {
int tempB = value.charAt(i);
if (tempB == '0' || tempB == '1') {
continue; // process next character.
// continue skips rest of loop
}
return false;
}
// no failures, so
return true;
没有的替代逻辑continue
可能是:
for(int i = 0; i < value.length(); i++) {
int tempB = value.charAt(i);
if (tempB != '0' && tempB != '1') {
return false;
}
}
// no failures, so
return true;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句