Сложность заключается в том, отделить ли детали с помощью " and "
или ","
, что зависит от того, сколько ненулевых деталей отображается справа от части, которую вы в данный момент печатаете. Остальное (печать имен и номеров) легко.
Следовательно, вы можете уменьшить количество ветвей, построив строку справа налево.
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();
}
или, в более общем случае:
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();
}