문제

So for school a task I have is to write a program that converts decimal to binary to hexadecimal.

So I'm running into a problem that when I call a method that takes a para of the 4 digit binary and returns the hexadecimal character using a switch statement. It throws a StackOverflowError at line 15 and 19.

package assignmentOne;

public class QuestionSix {

public static void main(String[] args) {
    new QuestionSix();
}

public QuestionSix() {
    System.out.println(getHex("01001110"));
} 

public String getHex(String binary) {
    StringBuilder hexBuilder = new StringBuilder();
    int startIndex = 0;
    int endIndex = 4;
    while(true) {
        hexBuilder.append(getHex(binary.substring(startIndex, endIndex)));

        startIndex += 4;
        endIndex += 4;

        if(startIndex >= binary.length())
            break;
    }
    return hexBuilder.toString();
}

public String getHexValue(String binarySet) {
    switch(binarySet) {
        default: 
            break;
        case "0000":
            return "0";
        case "0001":
            return "1";
        case "0010":
            return "2";
        case "0011":
            return "3";
        case "0100":
            return "4";
        case "0101":
            return "5";
        case "0110":
            return "6";
        case "0111":
            return "7";
        case "1000":
            return "8";
        case "1001":
            return "9";
        case "1010":
            return "A";
        case "1011":
            return "B";
        case "1100":
            return "C";
        case "1101":
            return "D";
        case "1110":
            return "E";
        case "1111":
            return "F";
    }
    return null;
}
}

And the error I'm getting is at http://pastebin.com/fx3mCtif

Thanks

도움이 되었습니까?

해결책

You're recursing unconditionally:

public String getHex(String binary) {
    StringBuilder hexBuilder = new StringBuilder();
    int startIndex = 0;
    int endIndex = 4;
    while(true) {
        hexBuilder.append(getHex(binary.substring(startIndex, endIndex)));
        // Irrelevant
    }
    // Irrelevant
}

Basically aside from a little initialization, the first thing you do in your method is call it again. That call will the method again... which will call the method again, etc.

I suspect you meant to call getHexValue, not getHex... making the call not recursive at all. Currently you don't call getHexValue at all.

다른 팁

Your method is running in infinite loop causing StackOverflowError.

I think

hexBuilder.append(getHex(binary.substring(startIndex, endIndex)));
                  ^^^^^^
            This recursion is causing infinite loop

should be

hexBuilder.append(getHexValue(binary.substring(startIndex, endIndex)));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top