I have the following method:
public static String format_String(int hours, int minutes, int seconds)
{
if(hours > 0 && minutes > 0 && seconds > 0) return hours + " hours, " + minutes + " minutes and " + seconds + " seconds.";
else if(hours > 0 && minutes > 0 && seconds == 0) return hours + " hours and " + minutes + " minutes.";
else if(hours > 0 && minutes == 0 && seconds > 0) return hours + " hours and " + seconds + " seconds.";
else if(hours > 0 && minutes == 0 && seconds == 0) return hours + " hours.";
else if(hours == 0 && minutes > 0 && seconds > 0) return minutes + " minutes and " + seconds + " seconds.";
else if(hours == 0 && minutes > 0 && seconds == 0) return minutes + " minutes.";
else //if(hours == 0 && minutes == 0 && seconds > 0)
return seconds + " seconds.";
}
Can this method be simplified?
The tricky part is whether to separate parts with
" and "or",", which depends on how many non-zero parts appear to the right of the part you are currently printing. The rest (printing the names and numbers) is easy.Hence you can reduce the number of branches by building the string from right-to-left.
or more generally: