Skip to main content
added 5 characters in body; edited title
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Refactoring code out of Hexadecimal converter using a switch statement

I don't like how there is a switchswitch statement which just sets a variable (hexadecimal) based on what the case is. I feel there is a better way to do this. Maybe, such as by using a hash-map!? I. I need the code to be flexible so that adding new characters and setting the hexadecimal is easy.

Refactoring code out of a switch statement

I don't like how there is a switch statement which just sets a variable (hexadecimal) based on what the case is. I feel there is a better way to do this. Maybe using a hash-map!? I need the code to be flexible so that adding new characters and setting the hexadecimal is easy.

Hexadecimal converter using a switch statement

I don't like how there is a switch statement which just sets a variable (hexadecimal) based on what the case is. I feel there is a better way to do this, such as by using a hash-map. I need the code to be flexible so that adding new characters and setting the hexadecimal is easy.

Tweeted twitter.com/#!/StackCodeReview/status/221190648932466689
Source Link
Decrypter
  • 377
  • 1
  • 2
  • 7

Refactoring code out of a switch statement

I need some help improving my code and wondering if I there is a better way to do the following:

StringBuilder buf = new StringBuilder(node.length() + 8);
        for (int i=0, n=node.length(); i<n; i++) {
            char c = node.charAt(i);
            String hexadecimal = "";
            switch (c) {
                case '"': hexadecimal = "\\22"; break;
                case '&': hexadecimal = "\\26"; break;
                case '\'': hexadecimal = "\\27"; break;
                case '/':  hexadecimal = "\\2f"; break;
                case ':': hexadecimal = "\\3a"; break;
                case '<': hexadecimal = "\\3c"; break;
                case '>': hexadecimal = "\\3e"; break;
                case '@': hexadecimal ="\\40"; break;
                case '\\':hexadecimal = "\\5c"; break;
                default: {
                    if (Character.isWhitespace(c)) {
                        hexadecimal = "\\20";
                    }else if(c > 127){
                        hexadecimal = "\\" + Integer.toHexString(c) + "\\";
                    }
                    else {
                        hexadecimal = String.valueOf(c);
                    }
                }
            }
            buf.append(hexadecimal);
        }
        return buf.toString();

I don't like how there is a switch statement which just sets a variable (hexadecimal) based on what the case is. I feel there is a better way to do this. Maybe using a hash-map!? I need the code to be flexible so that adding new characters and setting the hexadecimal is easy.