Switch Rule With Multiple Statments

Viewed 2305

How can I use switch rule with multiple statements? For ex. convert this:

switch (choice) {
            case 1:
                ans = inchesToCentimeters(num);
                System.out.println(ans);
                break;
        }

To something like this (I don't know how to do it obviously but this is just a guess):

switch (choice) {
            case 1 -> ans = inchesToCentimeters(num);
                   -> System.out.println(ans);
        }

Any help is much appreciated and thank you in advance.

1 Answers

In JDK 12 should be changed like this:

switch (choice) {
    case 1 -> {
        ans = inchesToCentimeters(num);
        System.out.println(ans);
    }
    case 2 -> {
        // next case
    }
}

Also, you could return result from switch and fix duplicated code:

double ans = switch(choice) {
    case 1 -> inchesToCentimeters(num);
    case 2 -> centimetersToInches(num);
    case 3 -> feetToCentimeters(num);
    case 4 -> centimetersToFeet(num);
    default -> throw new IllegalArgumentException("Bad choice: " + choice);
};

System.out.println(ans);
Related