programmers5
programmers5

Reputation: 336

Java asking for return statement for class

I have the following code:

public class BinaryDecoder{
public static void main(String[] args){
    String binNum = "110101"; 
    int res = 0;
    for (int i = 0;i<binNum.length();i++){
        //res += parseDigit(binNum.charAt(i),binNum);
    }
//  System.out.println(res);

}
public static int parseDigit(int index, String binNum){
    switch (binNum.charAt(index)){
        case 0:
        break;
        case 1:
        int val = (int) Math.pow(2,-index+binNum.length());
        return val;
        }
}

}

And I am getting the error: BinaryDecoder.java:30: error: missing return statement } ^

I may have interpreted this wrong, but why would my class BinaryDecode have or even need a return statement? Is there something else wrong with the code?

Note: I am fairly new in java, so sorry if there are any obvious errors in my code.

Upvotes: 0

Views: 745

Answers (3)

xhocquet
xhocquet

Reputation: 380

The problem has to do with your parseDigit class.

If the case is 0, there is no return and the compiling fails. Try this:

public static int parseDigit(int index, String binNum){
    switch (binNum.charAt(index)){
        case 0:
        return SOMETHING;
        break;
        case 1:
        int val = (int) Math.pow(2,-index+binNum.length());
        return val;
        default:
        return -1;
        break;
    }

Upvotes: 2

fzzfzzfzz
fzzfzzfzz

Reputation: 1248

The class isn't what needs a return statement, the parseDigit method is. In its signature, it claims to return an int. You do have a return statement for that method, but because it is inside a switch statement, it isn't guaranteed to happen.

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 994061

It's not the class that needs a return statement; it is the parseDigit function, which you have declared as returning an int. It is an error to have the possibility of not returning a value when you have said it will.

Upvotes: 5

Related Questions