Skip to content
Advertisement

How to remove duplicate cases in switch in java

I have sonarQube running but it says that there are duplicates within these lines of code. How do resolve this in a switch statement? I am just learning how unit testing in java works so any help would be great!

switch () {
    case "M":
        campusLogo = "/watermark_main.png";
        break;
    case "IN":
        campusLogo = "/Watermark_IN.png";
        break;
    case "WA":
        campusLogo = "/Watermark_WA.png";
        break;
    case "MO":
        campusLogo = "/Watermark_MO.png";
        break;
    case "NC":
        campusLogo = "/Watermark_NC.png";
        break;
    case "NV":
        campusLogo = "/Watermark_NV.png";
        break;
    case "OH":
        campusLogo = "/Watermark_OH.png";
        break;
    case "TN":
        campusLogo = "/Watermark_TN.png";
        break;
    case "TX":
        campusLogo = "/Watermark_TX.png";
        break;

    default:
        campusLogo = "/watermark_main.png";
}

Advertisement

Answer

I think below solution should work for you:

switch (choice) {
    case "IN":
    case "WA":
    case "MO":
    case "NC":
    case "NV":
    case "OH":
    case "TN":
    case "TX":
        campusLogo = "/Watermark_" + choice + ".png";
        break;

    default:
        campusLogo = "/watermark_main.png";
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement