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.
The code you've provided can be made into a
switch-expression
like that:The length of the
parts
array should be used inside the parentheses()
of theswitch
. And each particular length (1
and2
) should be used as a case-constant.The
default
case covers all unspecified array sizes.