메소드 오버로딩 예제 - 시분초
Method overloading practice
Udemy - JavaMasterClass by Tim Buchalka
- minutes 인자와 seconds 인자를 받는 getDurationString이라는 메소드를 만든다.
- 첫번째 인자가 0보다 크거나 같음을 확인한다.
- 두번째 인자가 0보다 크거나 같음을 확인한다.
- 위 조건을 통과하지 못하면 “Invalid value” 메세지를 돌려준다.
- 인자가 위 조건을 충족하면 시분초를 나타내는 다음의 포맷을 가진 문자열을 돌려준다. “HH MM SS”
-Source :
https://www.udemy.com/user/learn-programming-academy/
나의 답안
public class Main {
public static void main(String[] args) {
System.out.println(getDurationString(65,45));
System.out.println(getDurationString(3945));
System.out.println(getDurationString(-41));
System.out.println(getDurationString(9,9));
}
public static String getDurationString (int minutes, int seconds) {
if (minutes < 0 || seconds < 0 || seconds > 59)
return "Invalid value";
return (minutes / 60 + "h " + minutes % 60 + "m " + seconds + "s");
}
public static String getDurationString (int seconds) {
if (seconds < 0)
return "Invalid value";
return getDurationString (seconds / 60, seconds % 60);
}
}
정답
public class Main {
private static final String INVALID_VALUE_MESSAGE = "Invalid Value";
public static void main(String[] args) {
System.out.println(getDurationString(65,45));
System.out.println(getDurationString(3945L));
System.out.println(getDurationString(-41));
System.out.println(getDurationString(9,9));
}
private static String getDurationString (long minutes, long seconds) {
if (minutes < 0 || seconds < 0 || seconds > 59)
return INVALID_VALUE_MESSAGE;
long hours = minutes / 60;
long remainingMinutes = minutes % 60;
String hoursString = hours + "h";
if(hours < 10) {
hoursString = "0" + hoursString;
}
String minutesString = remainingMinutes + "m";
if(remainingMinutes < 10) {
minutesString = "0" + minutesString;
}
String secondsString = seconds + "h";
if(seconds < 10) {
secondsString = "0" + secondsString;
}
return hoursString + " " + minutesString + " " + secondsString;
}
private static String getDurationString (long seconds) {
if (seconds < 0)
return INVALID_VALUE_MESSAGE;
long minutes = seconds / 60;
long remainingSeconds = seconds % 60;
return getDurationString (minutes, remainingSeconds);
}
}