I have written a little program that calculates the time by given strings.
A time string in the context of this program consists of a number and a following letter that can be s, m, h, or d.
You can enter something like this:
java TimeCalculator 443432s 34234m 34323m 32344234s 8h 23d 12h
It than calculates the time and prints it out in an readable format:
450 days 22 hours 18 minutes 6 seconds
I want to ask you, how I can improve the readability and maybe also the performance. I dont tried to design the program object oriented because I think the program is to small for that. But if you have another opinion on that, please let me know!
public class TimeCalculator {
private static final int MINUTE_IN_SECONDS = 60;
private static final int HOUR_IN_SECONDS = 3600;
private static final int DAY_IN_SECONDS = 86400;
private static int seconds = 0;
public static void main(String[] args) {
if (args.length == 0 || args[0].contains("help")) {
showHelp();
return;
}
for (String arg : args) {
timeStringToSeconds(arg);
}
printNewTimeString();
}
private static void timeStringToSeconds(String timeString) {
if (timeString.contains("s")) {
timeString = timeString.replace("s", "");
seconds += Integer.parseInt(timeString);
} else if (timeString.contains("m")) {
timeString = timeString.replace("m", "");
seconds += Integer.parseInt(timeString) * MINUTE_IN_SECONDS;
} else if (timeString.contains("h")) {
timeString = timeString.replace("h", "");
seconds += Integer.parseInt(timeString) * HOUR_IN_SECONDS;
} else if (timeString.contains("d")) {
timeString = timeString.replace("d", "");
seconds += Integer.parseInt(timeString) * DAY_IN_SECONDS;
}
}
private static void printNewTimeString() {
String newTimeString = new String();
// calculate days
int days = 0;
while (seconds >= DAY_IN_SECONDS) {
days++;
seconds -= DAY_IN_SECONDS;
}
if (days > 0) {
newTimeString += days + " days ";
}
// calculate hours
int hours = 0;
while(seconds >= HOUR_IN_SECONDS) {
hours++;
seconds -= HOUR_IN_SECONDS;
}
if (hours > 0) {
newTimeString += hours + " hours ";
}
// calculate minutes
int minutes = 0;
while (seconds >= MINUTE_IN_SECONDS) {
minutes++;
seconds -= MINUTE_IN_SECONDS;
}
if (minutes > 0) {
newTimeString += minutes + " minutes ";
}
// calculate seconds
if (seconds > 0) {
newTimeString += seconds + " seconds ";
}
System.out.println(newTimeString);
}
private static void showHelp() {
System.out.println("This Program converts time strings to an ordered string that makes the time");
System.out.println("information better understandable\n");
System.out.println("You can enter something like this: ");
System.out.println("java TimeCalculator 534s 400d 32453s 234h");
System.out.println("The output will be this: ");
System.out.println("410 days 3 hours 9 minutes 47 seconds");
System.out.println("Available characters: d, h, m, s");
}
}