Jonas Aqua
Jonas Aqua

Reputation: 45

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.

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.

Upvotes: 0

Views: 642

Answers (1)

Keammoort
Keammoort

Reputation: 3075

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). Much better solution would be to use a loop and StringBuilder.

Solution with StringBuilder (in case you want to boost your performance, this code executes about 4 times faster):

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();
}

Upvotes: 3

Related Questions