forked from prmr/DesignBook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwelveDays2.java
More file actions
108 lines (98 loc) · 2.6 KB
/
TwelveDays2.java
File metadata and controls
108 lines (98 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*******************************************************************************
* Companion code for the book "Introduction to Software Design with Java"
* by Martin P. Robillard.
*
* Copyright (C) 2019 by Martin P. Robillard
*
* This code is licensed under a Creative Commons
* Attribution-NonCommercial-NoDerivatives 4.0 International License.
*
* See http://creativecommons.org/licenses/by-nc-nd/4.0/
*******************************************************************************/
package chapter1;
/**
* Outputs the text of the poem "The Twelve Days of Christmas"
* to the console. The code leverages the natural recursion in
* the structure of the poem. This version allows users to
* display days using digits by passing in the command-line
* argument "digits".
*/
public class TwelveDays2
{
private static boolean asDigits = false;
public static void main(String[] args)
{
detectDigits(args);
System.out.println(poem());
}
static void detectDigits(String[] args)
{
asDigits = args != null && args.length > 0 && args[0].equals("digits");
}
static String[] DAYS = {"first", "second", "third", "fourth",
"fifth", "sixth", "seventh", "eighth",
"ninth", "tenth", "eleventh", "twelfth"};
static String[] DAYS_DIGITS = {"1st", "2nd", "3rd", "4th",
"5th", "6th", "7th", "8th",
"9th", "10th", "11th", "12th"};
static String day(int day)
{
if(asDigits)
{
return DAYS_DIGITS[day];
}
else
{
return DAYS[day];
}
}
static String[] GIFTS = {
"a partridge in a pear tree",
"two turtle doves",
"three French Hens",
"four Calling Birds",
"five Golden Rings",
"six Geese a Laying",
"seven Swans a Swimming",
"eight Maids a Milking",
"nine Ladies Dancing",
"ten Lords a Leaping",
"eleven Pipers Piping",
"twelve Drummers Drumming"
};
/*
* Returns the first line in the verse for a given day.
*/
static String firstLine(int day)
{
return "On the " + day(day) +
" day of Christmas my true love sent to me:\n";
}
/*
* Returns a string that lists all the gifts received on a given
* day.
*/
static String allGifts(int day)
{
if( day == 0 )
{
return "and " + GIFTS[0];
}
else
{
return GIFTS[day] + "\n" + allGifts(day-1);
}
}
/*
* Returns the text of the entire poem.
*/
static String poem()
{
String poem = firstLine(0) + GIFTS[0] + "\n\n";
for( int day = 1; day < 12; day++ )
{
poem += firstLine(day) + allGifts(day) + "\n\n";
}
return poem;
}
}