/*******************************************************************************
* Companion code for the book "Introduction to Software Design with Java",
* 2nd edition by Martin P. Robillard.
*
* Copyright (C) 2023 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 e2.chapter1;
/**
* Outputs the text of the poem "The Twelve Days of Christmas" to the console.
* This program generates the same output as Ian Phillips' contest-winning
* obfuscated C code (http://www.ioccc.org/1988/phillipps.c), but with a
* self-evident structure that leverages the recursion in the poem.
*/
public class TwelveDays {
public static void (String[] args) {
System.out.(poem());
}
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 )
{
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 (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 = + "\n\n";
for( int day = 1; day < 12; day++ )
{
poem += firstLine(day) + allGifts(day) + "\n\n";
}
return poem;
}
}
This method is intended for the "standard output", i.e., those intended to
a user in a normal flow of events. If you need to print error messages, or
logging/debugging information, you can instead use the "standard error" stream,
with System.err.println
.
This method is intended for the "standard output", i.e., those intended to
a user in a normal flow of events. If you need to print error messages, or
logging/debugging information, you can instead use the "standard error" stream,
with System.err.println
.
This method is clear because it is short and it abstracts an .
This method is clear because it is short and it abstracts an .
except for the argument type, which can be replaced with a vararg parameter
String...
. The result is public static void main(String... args)
except for the argument type, which can be replaced with a vararg parameter
String...
. The result is public static void main(String... args)
The main method must have a single parameter, which must be an array of String
.
The values of this array are supplied when starting the program, typically through the
command line.
The main method must have a single parameter, which must be an array of String
.
The values of this array are supplied when starting the program, typically through the
command line.
This is that can change from the header declaration of a main
method:
the name of the parameter can be any (valid) Java identifier.
This is that can change from the header declaration of a main
method:
the name of the parameter can be any (valid) Java identifier.
static
is a modifier that indicates that a declaration is not associated with
any instance of a class (see Appendix A.4).
static
is a modifier that indicates that a declaration is not associated with
any instance of a class (see Appendix A.4).
void
is a keyword used in place of a return type to indicate that a method does
not return a value.
void
is a keyword used in place of a return type to indicate that a method does
not return a value.
The main
method is the entry point of any Java program.
It must
have the exact signature main( )
. Otherwise,
the main
method is like any other and can be called by other methods in
the program, although that is not a common practice, or even recommended.
The main
method is the entry point of any Java program.
It must
have the exact signature main( )
. Otherwise,
the main
method is like any other and can be called by other methods in
the program, although that is not a common practice, or even recommended.
public
is an access modifier that indicates that a declaration is visible
(can be accessed) by any code (see chapter 2.3).
public
is an access modifier that indicates that a declaration is visible
(can be accessed) by any code (see chapter 2.3).
No matter how small a program, it can be difficult to completely avoid annoying corner cases.
No matter how small a program, it can be difficult to completely avoid annoying corner cases.
This statement shows a typical implementation of a
recursive algorithm. The function creates a list of gifts by
adding the last gift (GIFTS[day]
) to a smaller lists of gifts
(allGifts(day-1)
).
This statement shows a typical implementation of a
recursive algorithm. The function creates a list of gifts by
adding the last gift (GIFTS[day]
) to a smaller lists of gifts
(allGifts(day-1)
).
String
class represents character strings. All
string literals in Java programs, such as "abc"
, are
implemented as instances of this class.
String
class represents character strings. All
string literals in Java programs, such as "abc"
, are
implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining
individual characters of the sequence, for comparing strings, for
searching strings, for extracting substrings, and for creating a
copy of a string with all characters translated to uppercase or to
lowercase. Case mapping is based on the Unicode Standard version
specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor
or method in this class will cause a NullPointerException
to be
thrown.
A String
represents a string in the UTF-16 format
in which supplementary characters are represented by surrogate
pairs (see the section Unicode
Character Representations in the Character
class for
more information).
Index values refer to char
code units, so a supplementary
character uses two positions in a String
.
The String
class provides methods for dealing with
Unicode code points (i.e., characters), in addition to those for
dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale
into account. The Collator
class provides methods for
finer-grain, locale-sensitive String comparison.
javac
compiler
may implement the operator with StringBuffer
, StringBuilder
,
or java.lang.invoke.StringConcatFactory
depending on the JDK version. The
implementation of string conversion is typically through the method toString
,
defined by Object
and inherited by all classes in Java.In the first verse, we don't add the conjunction "and" in front of "a partridge". We need to handle this separately.
In the first verse, we don't add the conjunction "and" in front of "a partridge". We need to handle this separately.
Console.charset()
if the Console
exists,
stdout.encoding otherwise.
Console.charset()
if the Console
exists,
stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println
methods in class PrintStream
.
The only parameterization involved maps directly to the problem domain, the day.
The only parameterization involved maps directly to the problem domain, the day.
To create the list of gifts for a given day, we can leverage the inherent recursion in the poem's structure to organize the code.
To create the list of gifts for a given day, we can leverage the inherent recursion in the poem's structure to organize the code.
System
class contains several useful class fields
and methods. It cannot be instantiated.
Among the facilities provided by the System
class
are standard input, standard output, and error output streams;
access to externally defined properties and environment
variables; a means of loading files and libraries; and a utility
method for quickly copying a portion of an array.System
class contains several useful class fields
and methods. It cannot be instantiated.
Among the facilities provided by the System
class
are standard input, standard output, and error output streams;
access to externally defined properties and environment
variables; a means of loading files and libraries; and a utility
method for quickly copying a portion of an array.the creation of the first line
the creation of the first line
In Java, to print something to the console, you can use the function
System..println()
, which is method println()
from
the static field out
of the System
class. In this case, we print
the result of the poem()
method to the console.
print(String)
and then
println()
.In Java, to print something to the console, you can use the function
System..println()
, which is method println()
from
the static field out
of the System
class. In this case, we print
the result of the poem()
method to the console.
print(String)
and then
println()
.x
- The String
to be printed.