Handout
Computer Science E-50a: Introduction to Computer Science Using Java, I
part 1
I. Description
Refer to the Savitch text (or your favorite Java reference) to reinforce
your comprehension of Java parameter passing mechanisms and other
constructs. Unless otherwise indicated, everything which the human
would type to the computer has been underlined. Everything which the
computer types is not.
Work carefully! The programming problems which are done on the
computer will be graded partly on the basis of style as well as correctness.
These problems are due prior to the start of lecture on Monday evening,
April 14. Get started as soon as possible!
II. Pencil-and-Paper Exercises
(15 points total)
[1] 5 points
Write Java code (it doesn’t have to be a complete program) that generates
two “random” integers, each between 1 and 7 (inclusive). Use a switch
statement to output one of the following three messages:
• A tie!
• You lose!
• You win!
Spring 2003
if the difference between the numbers is zero
if the difference between the numbers is 1, 3, or 5
if the difference between the numbers is 2, 4, or 6
Dr. S. J. Eigen
Computer Science E-50a: Introduction to Computer Science Using Java, I
Page 2
[2] 5 points
Precisely what is printed by the following horrible program? In
answering this question, draw little boxes that clearly show how the values
of all the different variables change as each instruction gets executed. (We
want you to demonstrate that you understand how parameter passing
works!)
class Prob2
{
static int foo (int a, int b)
{ return (a + b); }
static int bar (int x)
{
x += 2; return (x * x); }
public static void main (String args[ ] )
{
int x = 2;
System.out.println("Foo = " + foo(x, 3) );
System.out.println("Foo = " + foo(x, 4) );
System.out.println("Bar = " + bar( -x ));
System.out.println("Bar = " + bar( foo(x+x, ++x) ));
}
}
[3] 5 points
In Java’s C h a r a c t e r class, there’s a method named
isJavaIdentifierStart(char ch). This method determines if
the char argument is permissible as the first character in a Java identifier.
A character may start a Java identifier if and only if it is (1) a letter; (2) a
currency symbol (i.e., ‘$’); or (3) a connecting punctuation character (i.e., ‘_’
which is the underscore).
This method returns true if the character may start a Java identifier; false
otherwise. Define your own version of isJavaIdentifierStart
Spring 2003
Unit Three Problem Set, part 1
Dr. s. J. Eigen
Computer Science E-50a: Introduction to Computer Science Using Java, I
Page 3
III. Programming Problems (up to 100 points)
For the problems in this section, be sure to follow the instructions on
electronic submission as described in http://www.fas.harvard.edu/~libe50a
[4] 15 points
(use file ThisOldMan.java)
Write a program to print the lyrics for the song “This Old Man”.
This old man, he played 1.
He played nick-nack on my drum;
With a nick-nack paddy-whack, give the dog a bone,
This old man came running home.
This old man, he played 2.
He played nick-nack on my shoe;
With a nick-nack paddy-whack, give the dog a bone,
This old man came running home.
…
…
Use the same technique demonstrated in lecture for the “Marching Ants”
song. The remaining verses are
3— on my tree
5— on my hive
7— up in heaven
9— on my spine
4— on my door
6— on my sticks
8— on my gate
10— on my hen
Alternative lyrics, as well as other nursery rhymes appear at
http://www.zelo.com/family/nursery/oldman.htm
Spring 2003
Unit Three Problem Set, part 1
Dr. s. J. Eigen
Computer Science E-50a: Introduction to Computer Science Using Java, I
[5]
10 points
Page 4
(use file LeapYear.java)
Write a “predicate” method
static boolean isLeapYear(int year)
that tests whether its argument repesents a “leap year,” i.e., a year with 366
days. Leap years are necessary to keep the calendar synchronized with the
sun because the earth revolves around this star once every 365.25 days.
Actually, that figure is not entirely precise, and so for all dates after 1582
the Gregorian Correction applies: the years that are divisible by 4 are
usually leap years (for example, 1996). However, years that are divisible
by 100 (for example, 1900) are not leap years; but years that are divisible by
400 are leap years (e.g., the year 2000).
Write a main method that tests your isLeapYear method. It should work
as shown here — asking the user for a year until the value -1 is typed. The
year value that is input should be passed to the isLeapYear method, which
then computes and returns the answer that gets printed by your main
program.
Type a year greater than 1582, or -1 to stop: 1996
1996 IS a leap year!
Type
1900
Type
2000
a year greater than 1582, or or -1 to stop: 1900
IS NOT a leap year!
a year greater than 1582, or or -1 to stop: 2000
IS a leap year!
Type a year greater than 1582, or or -1 to stop: -1
Thank you for using this program!
For those of you interested in the background of leap years, Sarah L. Maher
w/information provided by Royal Greenwich Observatory has written the following. See
also http://www.rog.nmm.ac.uk/leaflets/leapyear/leapyear.html
Our solar year (the time required for Earth to travel once around the Sun) is 365.24219
days.
Our calendar year is either 365 days in non leap years or 366 days in leap years. A leap
year every 4 years gives us 365.25 days, sending our seasons off course and eventually in
Spring 2003
Unit Three Problem Set, part 1
Dr. s. J. Eigen
Computer Science E-50a: Introduction to Computer Science Using Java, I
Page 5
the wrong months. To change .25 days to .24219, we skip a few leap days every one
hundred years or so.
Here’s the history:
The Romans originally had a 355-day calendar. To keep up with the seasons, an extra
22 or 23-day month was inserted every second year. For reasons unknown, this extra
month was only observed now and then. By Julius Caesar’s time, the seasons no longer
occurred at the same calendar periods as history had shown. To correct this, Caesar
eliminated the extra month and added one or two extra days to the end of various
months (his month included, which was Quintilis, later renamed Juliuswe know it as July).
This extended the calendar to 365 days. Also intended was an extra calendar day every
fourth year (following the 28th day of Februarius). However, after Caesar’s death in 44
B.C., the calendars were written with an extra day every 3 years instead of every 4 until
corrected in 8 A.D. So again, the calendar drifted away from the seasons. By 1582,
Pope Gregory XIII recognized that Easter would eventually become closer and closer to
Christmas. The calendar was reformed so that a leap day would occur in any year that is
divisible by 4 but not divisible by 100 except when the year is divisible by 400. Thus
1600 and 2000, although century marks, have a Leap Day.
The calendar we use today, known as the Gregorian calendar, makes our year 365.2425
days only off from our solar year by .00031, which amounts to only one day’s error after
4,000 years.
[6] 15 points
(use file License.java)
Write a Java program that prints 20 “random” license plate numbers,
each one consisting of three randomly-chosen digits followed by three
randomly chosen upper-case letters. The first digit cannot be zero.
Spring 2003
Unit Three Problem Set, part 1
Dr. s. J. Eigen
Computer Science E-50a: Introduction to Computer Science Using Java, I
[7] 15 points
Page 6
(use file Initials.java)
Write a Java method named getInitials that accepts a String value in its
only parameter. Assume the actual argument passed to this parameter is
some person’s full name and contains their first, middle and last names.
This method should return a String containing this person’s “initials.”
Use the built-in String methods such as length(), charAt(),
compareTo(), indexOf(), concat(), and so on.
For example, getInitials(“William H. Gates, III”) should
return the value WHG. Assume that precisely one space character separates
the first name from the middle name, and the middle name from the last
name.
Be sure you write a main method that tests your program out
thoroughly; it should read in a character string that the user types on the
keyboard using one of the SavitchIn methods. Describe carefully whether
and why your method will fail if you pass as an argument to it a String that
lacks a middle name.
[8] 15 points
(use file Nim.java)
Write a program that plays a complete game of Nim against a human
opponent. In this very simple game, the players start with a pile of 11
match sticks. Each player takes a turn at removing one, two, or three
matches from the pile. The player that ends up with the last stick is the
loser. Here’s a simple interaction to illustrate how your program will look
in action:
WELCOME TO THE GAME OF NIM!
How many matches do you want? -1
That’s an illegal move. Choose 1, 2, or 3 matches.
How many matches do you want? 1
Human takes one match, leaving 10
Computer takes 1 match, leaving 9
How many matches do you want? 1
Spring 2003
Unit Three Problem Set, part 1
Dr. s. J. Eigen
Computer Science E-50a: Introduction to Computer Science Using Java, I
Page 7
Human takes one match, leaving 8
Computer takes 3 matches, leaving 5
How many matches do you want? 2
Human takes 2 matches, leaving 3
Computer takes 2 matches, leaving 1
Computer wins the game!
Note that the human always goes first, and whenever the human makes a
“stupid move”, the computer will win the game. If the computer is in a
situation where it knows it cannot win (e.g., it has 5 matches), have it pick
an appropriate “random” number of matches.
Note also that the output from the program is “grammatical.” By this we
mean the program prints the singular and plural forms of the word match
correctly (e.g., “1 match” versus “2 matches”). Also note that the program
will not allow the human to make an illegal move.
Use a switch statement in the part of your program that deals with the
computer’s strategy.
Spring 2003
Unit Three Problem Set, part 1
Dr. s. J. Eigen
Computer Science E-50a: Introduction to Computer Science Using Java, I
[9]
10 points
Page 8
(use file Baseball.java)
THIS PROBLEM IS REQUIRED FOR ALL GRADUATE-CREDIT
STUDENTS. Undergraduate-credit students may solve the problem for
“extra credit.”
Johann VanDerDoe, a baseball player, has the following lifetime hitting
percentages:
Out
Single
Triple
63.4%
19.0%
1.1%
Walk10.3%
Double
Home run
4.9%
1.3%
Using “random numbers” write a Java program to simulate 1000 times at
bat for Johann, counting (and printing out) the number of outs, walks,
singles, and so on, and then calculating his batting average, which is
(# of hits) / (1000 - # of walks)
Note that singles, doubles, triples and home runs are all considered to be
“hits.” Hint: if the random numbers you generate are each between 0 and
1, then a random number which is less than or equal to .634 should count
as an “out.” Random numbers greater than .634 but less than or equal to
.737 represent a “walk,” and so on. Think about it!
[10]
10 points
Given the time of day in terms of an hour, minute, second and “day half”
(i.e., AM or PM), write a static Java method named fractionOfDay to
calculate and return the fraction of the day (a value of type double) that has
elapsed since midnight (12:00 AM). For example,
System.out.print(fractionOfDay ( 12, 0, 0, 'A'));
would print 0.0
System.out.print(fractionOfDay ( 12, 0, 0, 'P'));
would print 0.5
System.out.print(fractionOfDay ( 11, 59, 59, 'P'));
would print 0.999988426
Write a main method that can produce a table like the following (use a
Spring 2003
Unit Three Problem Set, part 1
Dr. s. J. Eigen
Computer Science E-50a: Introduction to Computer Science Using Java, I
Page 9
couple of for loops):
Time
12:00 AM
1:00 AM
2:00 AM
3:00 AM
4:00 AM
5:00 AM
6:00 AM
7:00 AM
8:00 AM
9:00 AM
10:00 AM
11:00 AM
12:00 PM
1:00 PM
2:00 PM
3:00 PM
4:00 PM
5:00 PM
6:00 PM
7:00 PM
8:00 PM
9:00 PM
10:00 PM
11:00 PM
Spring 2003
Fraction since midnight
0
0.041666667
0.083333333
0.125
0.166666667
0.208333333
0.25
0.291666667
0.333333333
0.375
0.416666667
0.458333333
0.5
0.541666667
0.583333333
0.625
0.666666667
0.708333333
0.75
0.791666667
0.833333333
0.875
0.916666667
0.958333333
Unit Three Problem Set, part 1
Dr. s. J. Eigen
© Copyright 2026 Paperzz