Given a time in numbers we can convert it into words. For example : 5 : 00 —— five o’clock 5 : 10 —— ten minutes past five 5 : 15 —— quarter past five 5 : 30 —— half past five 5 : 40 —— twenty minutes to six 5 : 45 —— quarter to six 5 : 47 —— thirteen minutes to six Write a program which first inputs two integers, the first between 1 and 12 (both inclusive) and second between 0 and 59 (both inclusive) and then prints out the time they represent, in words.
import java.util.*;
public class TimeToWord {
int h, m;
String[] N = {
"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
"Twelve", "Thirteen", "FourTeen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty",
"Twenty One", "Twenty Two", "Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six",
"Twenty Seven", "Twenty Eight", "Twenty Nine"
};
TimeToWord(int hr, int min) {
h = hr;
m = min;
}
String getName() {
if (m == 0)
return String.format("%s o'clock", N[h - 1]);
else if (m == 15)
return String.format("Quarter past %s", N[h - 1]);
else if (m == 30)
return String.format("Half past %s", N[h - 1]);
else if (m == 45)
return String.format("Quarter to %s", N[h]);
else if (m < 30)
return String.format("%s minutes past %s", N[m - 1], N[h - 1]);
else
return String.format("%s minutes to %s", N[60 - m - 1], N[h]);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Time as hr,min :");
String time = sc.next().trim();
int ind = time.indexOf(',');
int hr = Integer.parseInt(time.substring(0, ind));
int min = Integer.parseInt(time.substring(ind + 1));
System.out.printf("%d:%d %s", hr, min, (new TimeToWord(hr, min)).getName());
sc.close();
}
}
Name | Type | Use |
---|---|---|
global | ||
h | int | to store hours |
m | int | to store minutes |
N | String[] | Name of numbers from 1 to 29 in a array |
void main() | ||
sc | Scanner | object used to take user input |
time | String | to store entered time |
ind | int | stores index of ',' in 'time' |
hr | int | parsed integer of substring of time from 0 to ind (hours) |
min | int | parsed integer of substring of time from ind+1 to end (minutes) |