The hard part is whether to separate the parts with " and "or ",", which depends on how many nonzero parts are displayed to the right of the part that you are currently printing. The rest (printing names and numbers) are simple.
Therefore, you can reduce the number of branches by building a row from right to left.
public static String format_String(int hours, int minutes, int seconds)
{
StringBuilder result = new StringBuilder(".");
String sep = "", nextSep = " and ";
if (seconds > 0) {
result.insert(0, " seconds").insert(0, seconds);
sep = nextSep;
nextSep = ", ";
}
if (minutes > 0) {
result.insert(0, sep).insert(0, " minutes").insert(0, minutes);
sep = nextSep;
nextSep = ", ";
}
if (hours > 0) {
result.insert(0, sep).insert(0, " hours").insert(0, hours);
}
return result.toString();
}
or more broadly:
public static String formatString(SortedMap<TimeUnit, Integer> parts) {
StringBuilder result = new StringBuilder(".");
String sep = "", nextSep = " and ";
for (Map.Entry<TimeUnit, Integer> e: parts.entrySet()) {
TimeUnit field = e.getKey();
Integer quantity = e.getValue();
if (quantity > 0) {
result.insert(0, sep)
.insert(0, field.toString().toLowerCase())
.insert(0, ' ')
.insert(0, quantity);
sep = nextSep;
nextSep = ", ";
}
}
return result.toString();
}
finnw source
share