forked from prmr/DesignBook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwelveDaysIterative.java
81 lines (75 loc) · 2.05 KB
/
TwelveDaysIterative.java
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
/*******************************************************************************
* 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. This version is iterative instead of recursive.
*/
public class TwelveDaysIterative
{
public static void main(String[] args)
{
System.out.println(poem());
System.out.println("---");
}
static String[] DAYS = {"first", "second", "third", "fourth",
"fifth", "sixth", "seventh", "eighth",
"ninth", "tenth", "eleventh", "twelfth"};
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 " + DAYS[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)
{
String result = "";
for( int i = day; i > 0; i-- )
{
result += GIFTS[i] + "\n";
}
result += "and " + GIFTS[0];
return result;
}
/*
* Returns the text of the entire poem.
*/
static String poem()
{
String poem = firstLine(0) + GIFTS[0];
for( int day = 1; day < 12; day++ )
{
poem += "\n\n" + firstLine(day) + allGifts(day);
}
return poem;
}
}