Skip to content

Commit 19511bb

Browse files
committed
added String.format section
1 parent 0639135 commit 19511bb

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

ch09/Format.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Example using the String.format method.
3+
*/
4+
public class Format {
5+
6+
/**
7+
* Returns a time string in 12-hour format.
8+
*
9+
* @param hour between 0 and 23
10+
* @param minute between 0 and 59
11+
*/
12+
public static String timeString(int hour, int minute) {
13+
String ampm;
14+
if (hour < 12) {
15+
ampm = "AM";
16+
if (hour == 0) {
17+
hour = 12; // midnight
18+
}
19+
} else {
20+
ampm = "PM";
21+
hour = hour - 12;
22+
}
23+
return String.format("%02d:%02d %s", hour, minute, ampm);
24+
}
25+
26+
public static void main(String[] args) {
27+
System.out.println(timeString(0, 0));
28+
System.out.println(timeString(7, 30));
29+
System.out.println(timeString(12, 5));
30+
System.out.println(timeString(23, 59));
31+
}
32+
33+
}

0 commit comments

Comments
 (0)