[英]Java: “Unexpected Type; required: Variable; found: value” by trying to return a value
If I want to compile this on BlueJ, it throws me an "Unexpected Type; required: Variable; found: value" Error at the first "" on line 3. 如果我想在BlueJ上编译它,它将抛出“意外类型;必需:变量;找到:值”行3上第一个“”错误。
public static String binaryCode(int i){
if(i<=1){
return "" += i%2;
}
return "" += i%2 += binaryCode(i/2);
}
Btw, it has to be a recursion, I know a Loop would work too but it has to be solved within a recursion. 顺便说一句,它必须是一个递归,我知道一个循环也可以,但是必须在一个递归中解决。 The program should return the binary value as a string from an int.
程序应从int以字符串形式返回二进制值。
Use + operator, not += 使用+运算符,而不是+ =
public static String binaryCode(int i) {
if (i <= 1) {
return "" + i%2;
}
return "" + i%2 + binaryCode(i/2);
}
Note that this is very inefficient solution. 请注意,这是非常低效的解决方案。 A lot of String objects gets created and has to be destroyed (Strings are immutable in Java).
许多String对象被创建并且必须销毁(Java中字符串是不可变的)。 Much better solution would be to use a loop and StringBuilder.
更好的解决方案是使用循环和StringBuilder。
Solution with StringBuilder (in case you want to boost your performance, this code executes about 4 times faster): StringBuilder的解决方案(如果您想提高性能,此代码的执行速度将提高约4倍):
public static String binaryCode(int n) {
StringBuilder sb = new StringBuilder();
for(int i = n; i > 0; i /= 2) {
sb.append(i%2);
}
return sb.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.