Java: How to transform int into string in this particular situation ? Also if I can't do it - how to remove the switch case labels?

StackOverflow https://stackoverflow.com/questions/22145281

  •  19-10-2022
  •  | 
  •  

Question

I'm talking about this code:

public class test {
    public static void main(String[] args) {
        int n = 27;
        int m = n;
        int r = m%16;
        String sum = "";

        for (int i=0; i<=3; i++){
            r = m%16;
            m = m/16;
            switch(r){
            case 10: System.out.print("A");
            }
            switch(r){
            case 11: System.out.print("B");
            }
            switch(r){
            case 12: System.out.print("C");
            }
            switch(r){
            case 13: System.out.print("D");
            }
            switch(r){
            case 14: System.out.print("E");
            }
            switch(r){
            case 15: System.out.print("F");
            }
            sum = sum + r;

            if (m==0){
                break;
            }
        }
        System.out.print(sum);
    }
}

I am trying to make a program which converts numbers from decimal to hex and I need to find out how to change 11, 12, 13, 14, 15 to A, B, C, D, E, F inside of my loop. I've searched a lot but couldn't find out how to do it. In this particular code the output is: B111 (for 11) and if there is no way to convert these integers into the needed letters, I would appreciate it if you just tell me how to remove the case label ( B111 - B, 11 (case label), 1 ).

Was it helpful?

Solution

why don't you use what java is providing you instead of re-inventing the wheel:

int n = 27;
String str = Integer.toString(n, 16);
System.out.println(str);

You can also use Integer.toHexString(n) instead of Integer.toString(n, 16).

And if you still want to do it yourself, here is the corrected version of your code:

int n = 27;
int m = n;
int r = m % 16;
String sum = "";

while (m!=0) {
    r = m % 16;
    m = m / 16;
    switch (r) {
    case 10:
        sum = "A" + sum;
        break;

    case 11:
        sum = "B" + sum;
        break;

    case 12:
        sum = "C" + sum;
        break;

    case 13:
        sum = "D" + sum;
        break;

    case 14:
        sum = "E" + sum;
        break;

    case 15:
        sum = "F" + sum;
        break;

    default:
        sum = r + sum;
    }
}
System.out.print(sum);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top