简体   繁体   中英

Failed on converting a decimal number to a hexadecimal string in Java

I'm a novice Java learner and I follow Introduction to Java Programming by D. Liang page by page.

Anyway, I've written a program that converts any given decimal number to a hexadecimal string (in theory at least). I leave the code below. My problem is, the code works occasionally. Ie, it works for number 127 but it does not for number 221. I wonder why does it do so.

PS I'm aware that there's an another very useful method for this operation but i would like to know why my solution does not work. It's important for me because i want to be a good programmer who knows what he does.

public static void main(String[] args) {

    //Create a Scanner
    Scanner input = new Scanner(System.in);

    //Prompt user to enter any decimal number
    System.out.println("Enter a decimal number, please: ");
    int decNum = input.nextInt();

    int division = decNum;
    String allDigits = "";

    //Calculate the digitZero
    allDigits += setDigit(division);
    //Calculate the other digits
    do{
        division = division / 16;
        allDigits+=setDigit(division);
    } while (division >= 16);

    //Reverse the string into a normal hexadecimal view
    allDigits = new StringBuilder(allDigits).reverse().toString();
    //Display the result
    System.out.println("" + allDigits);
}

public static String setDigit(int Number) {
    int division = Number;
    int digit = division % 16;
    String hexDigits = "";
    if (digit > 9) {
        switch (digit) {
            case 10:
                hexDigits += "A";
            case 11:
                hexDigits += "B";
            case 12:
                hexDigits += "C";
            case 13:
                hexDigits += "D";
            case 14:
                hexDigits += "E";
            case 15:
                hexDigits += "F";
        }
    } else {
        hexDigits += Integer.toString(digit);
    }
    return hexDigits;
}

You forget about break; in the end of every case statement. From JLS :

If one of the case constants is equal to the value of the expression, then we say that the case matches, and all statements after the matching case label in the switch block, if any, are executed in sequence.

Try to replace your switch block with:

    switch (digit) {
        case 10:
            hexDigits += "A";
            break;
        case 11:
            hexDigits += "B";
            break;
        case 12:
            hexDigits += "C";
            break;
        case 13:
            hexDigits += "D";
            break;
        case 14:
            hexDigits += "E";
            break;
        case 15:
            hexDigits += "F";
            break;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM