Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch on two-character string beginning with number

I'm trying to write a piece of code that takes in a two digit hex number, e.g. "0C", and compares it to a list.

I'm using Java 6 so can't switch on a string and was initially planning on using switch on Enums but didn't realise that Enums have to start with a letter.

Is there a simple way to achieve something like the following without a whole series of "if, else if..." statements?:

public void code(String oc) {

switch (oc) {
    case 00:
        // do something
        break;
    case 0A:
        // do something else
        break;
    case A1:
                   ....
             }

Thanks, Robert.

like image 894
Robert Avatar asked Dec 05 '25 19:12

Robert


2 Answers

In Java 6, it is not possible to do this directly. You have to convert the String values to numbers (somehow), and then switch on the numbers. For instance:

switch (Integer.parseInt(oc, 16)) {
case 0x00:
    // do something
    break;
case 0x0A:
    // do something else
    break;
case 0xA1:
    ....
}

The string to number conversion is relatively expensive, and probably negates the performance benefit of using a switch ... unless you have a large number of distinct cases.

like image 100
Stephen C Avatar answered Dec 08 '25 07:12

Stephen C


You can use an enum, just put a letter in front, like this:

public enum MyEnum {
    X00,
    X0A,
    XA1
    // etc
}

public void code(String oc) {

    switch (MyEnum.valueOf("X" + oc)) { 
        case X00:
            // do something
            break;
        case X0A:
            // do something
            break;
        case XA1:
            // do something
            break;
     }
}
like image 39
Bohemian Avatar answered Dec 08 '25 07:12

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!