kaderud
kaderud

Reputation: 5497

How to improve (string) Switch-statement with cleaner / better code?

I'm by no means a professional Java developer, I code for fun to solve various problems/improve existing solutions, mostly for myself. I'm self-taught so I probably lack some fundamental Java/programming skills.

I am wondering if there is a better way to improve the following code segment.

I am parsing a web site and have a need to translate the incoming data to localized language. For this I use a simple switch/case scenario for the parsed String.

Could this be improved with something else? Map/HashMap?

Example-code:

String mCity = "Soelden";
switch (mCity) {
  case "Crans Montana"  : mCity = "Crans-Montana";  break;
  case "Soelden"        : mCity = "Sölden";         break;
  case "Val d Isere"    : mCity = "Val d'Isere";    break;
  case "St. Moritz"     : mCity = "Sankt Moritz";   break;
}

Upvotes: 2

Views: 193

Answers (3)

qwazer
qwazer

Reputation: 7521

My version:

import java.util.HashMap;
import java.util.Map;

public class MExample {

    private static Map<String,String>  map = new HashMap<String, String>();

    static {
        map.put("Crans Montana", "Crans-Montana");
        map.put("Soelden", "Sölden");
        map.put("Val d Isere", "Val d'Isere");
        map.put("St. Moritz", "Sankt Moritz");
    }


    public static String normalize(String s){
        String result = map.get(s);
        return (result != null) ? result : s;
    }

 //in-place test
    public static void main(String[] args) {
        System.out.println("v1 = " + normalize("St. Moritz")); 
        System.out.println("v2 = " + normalize("12"));
    }
}

Upvotes: 2

user1907906
user1907906

Reputation:

Map<String, String> cities = new HashMap<>();
cities.put("Crans Montana", "Crans-Montana");
cities.put("Soelden", "Sölden");
// more cities.put(...)

String mCity = "Soelden";
String mCityLocalized = cities.get(mCity); // will be "Sölden"

If you want to translate to different cities, you can use a nested structure.

Upvotes: 2

oschlueter
oschlueter

Reputation: 2698

here's an example:

import java.util.HashMap;
import java.util.Map;

public final class Translator {

    private Map<String, String> translation;

    public Translator() {
        translation = new HashMap<>();
        translation.put("Crans Montana", "Crans-Montana");
        translation.put("Soelden", "Sölden");
        translation.put("Val d Isere", "Val d'Isere");
        translation.put("St. Moritz", "Sankt Moritz");
    }

    public String translate(String input) {
        String result = this.translation.get(input);
        return (result != null) ? result : "";
    }

    public static void main(String[] args) {
        Translator t = new Translator();

        System.out.println(t.translate("Soelden")); // prints Sölden
    }
}

Upvotes: 3

Related Questions