fork(2) download
  1. class TalkingClock {
  2. private static final String[] zeroToTwelve = { "zero", "one", "two", "three", "four", "five", "six", "seven",
  3. "eight", "nine", "ten", "eleven", "twelve" };
  4. private static final String[] teens = { "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
  5. "nineteen" };
  6. private static final String[] twentyToFifty = { "twenty", "thirty", "fourty", "fifty" };
  7. private static final String PREFIX = "It's";
  8.  
  9. public static String hourToWords(String hourString) {
  10. int hour = Integer.parseInt(hourString);
  11. String suffix = "am";
  12. if (hour > 11) {
  13. suffix = "pm";
  14. }
  15. if (hour > 12) {
  16. hour = hour - 12;
  17. }
  18. if (hour == 0) {
  19. hour = 12;
  20. }
  21. String hourInWords = zeroToTwelve[hour] + " " + suffix;
  22. return hourInWords;
  23. }
  24.  
  25. public static String minutesToWords(String minString) {
  26. int minutes = Integer.parseInt(minString);
  27. String minutesString = "";
  28. if (minutes == 0) {
  29. // default value of minutesString
  30. } else if (minutes < 10) {
  31. minutesString = "oh " + zeroToTwelve[minutes];
  32. } else if (minutes < 13) {
  33. minutesString = zeroToTwelve[minutes];
  34. } else if (minutes < 20) {
  35. minutesString = teens[minutes - 13];
  36. } else if ((minutes % 10) == 0) {
  37. minutesString = twentyToFifty[Math.floorDiv(minutes, 20)];
  38. } else {
  39. minutesString = twentyToFifty[Math.floorDiv(minutes, 10) - 2] + " " + zeroToTwelve[(minutes % 10)];
  40. }
  41. return minutesString;
  42. }
  43.  
  44. private static String[] parseStringTimeToArray(String time) {
  45. if (time == null) {
  46. throw new IllegalArgumentException("The input time must not be null");
  47. }
  48. String[] timeArr = time.split(":");
  49. if (timeArr.length != 2) {
  50. throw new IllegalArgumentException("The input time must be in format \"HH:MM\"");
  51. }
  52. return timeArr;
  53. }
  54.  
  55. public static String timeToWords(String time) {
  56. String[] parsedTime = parseStringTimeToArray(time);
  57. String[] hourWithSuffix = hourToWords(parsedTime[0]).split(" ");
  58. String hour = hourWithSuffix[0];
  59. String suffix = hourWithSuffix[1];
  60. String minutes = minutesToWords(parsedTime[1]);
  61. if ("".equals(minutes)) {
  62. return PREFIX + " " + hour + " " + suffix;
  63. } else {
  64. return PREFIX + " " + hour + " " + minutes + " " + suffix;
  65. }
  66.  
  67. }
  68.  
  69. public static void main(String[] args) {
  70. String[] times = { "00:00", "01:30", "12:05", "14:01", "20:29", "21:00" };
  71. for (String time : times) {
  72. System.out.println(timeToWords(time));
  73. }
  74.  
  75. }
  76. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
It's twelve am
It's one thirty am
It's twelve oh five pm
It's two oh one pm
It's eight twenty nine pm
It's nine pm