Home > Back-end >  Changing a chain of If-statements into a Switch-expression
Changing a chain of If-statements into a Switch-expression

Time:05-31

I'm trying to convert the below if statement into a switch expression.

public static int parseDays(String durationString) {
    String[] parts = durationString.split(" ");
    if (parts.length == 2) {
        return unitValueCalculation(parts[1], parts[0]);
    }
    else if (parts.length == 1)
    {
        if (parts[0].equalsIgnoreCase("once")) return 1;
    }
    return 0;
}

This is what I've got:

 public static int parseDays(String durationString) {
       
        switch (durationString) {
            case durationString.split(" ").length  == 2 -> unitValueCalculation(parts[1], parts[2]);
        }

I'm not sure what to do about the case statement, though.

Any ideas would be appreciated.

CodePudding user response:

The code you've provided can be made into a switch-expression like that:

public static int parseDays(String durationString) {
    String[] parts = durationString.split(" ");
    
    return switch(parts.length) {
        case 2 -> unitValueCalculation(parts[1], parts[0]);
        case 1 -> parts[0].equalsIgnoreCase("once") ? 1 : 0;
        default -> 0;
    };
}

The length of the parts array should be used inside the parentheses () of the switch. And each particular length (1 and 2) should be used as a case-constant.

The default case covers all unspecified array sizes.

  • Related