Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Outline
Hungry
Dice
Java Programming
Code Examples for Week 2
Alice E. Fischer
January 29 and Feb 3 2015
Java Programming - L2. . .
1/31
Birthday Day
Outline
Hungry
Dice
Hungry
In-class Exercise
Dice
Birthday Day
Homework
Java Programming - L2. . .
2/31
Birthday Day
Outline
Hungry
Dice
Example: Hungry
Purpose and new elements
Code
Output
Java Programming - L2. . .
3/31
Birthday Day
Outline
Hungry
Dice
Purpose and New Elements
This silly program introduces the dynamic world.
New elements are:
I
A class with two data members, one of them final.
I
Initialization of a final member in the class definition.
I
A main function that instantiates a Hungry object and
executes its primary method.
I
Use of the infinite for loop with an if...break.
I
Style: comment lines before functions.
Java Programming - L2. . .
4/31
Birthday Day
Outline
Hungry
Dice
Birthday Day
Class Skeleton
import java.util.Scanner;
public class Hungry {
final int full = 17;
int level = 0;
// Demand 17 jellybeans.
// Count the beans you have.
// ----------------------------------------------public static void main (String args[]) {
Hungry H = new Hungry();
H.go();
}
// ----------------------------------------------public void go () { ...
}
}
Java Programming - L2. . .
5/31
Outline
Hungry
Dice
Birthday Day
The Primary method
// --------------------------------------------------public void go () {
Scanner sc = new Scanner(System.in);
String s;
int n;
System.out.println( "\nHey, Joe, I’m hungry...");
for(;;){
n = sc.nextInt();
level += n;
if (level >= full) break;
System.out.println (" Thank you...more...?");
}
System.out.println(" Thank you. Come again...\n");
}
Java Programming - L2. . .
6/31
Outline
Hungry
Dice
Birthday Day
Output
Hey, Joe, I’m hungry. Feed me some jellybeans.
How many do you have?
18
Thank you. Come again tomorrow!
---------------------------------------------------------Hey, Joe, I’m hungry. Feed me some jellybeans.
How many do you have?
4
Thank you for 4 jellybeans.
I’m still hungry. How many more do you have?
15
Thank you. Come again tomorrow!
Java Programming - L2. . .
7/31
Outline
Hungry
Dice
Birthday Day
In-class Exercise
Modify the Hungry Program.
I
Start with the Hungry program
I
Add a constructor to the Hungry class, with one parameter,
the target number of Jellybeans.
Java Programming - L2. . .
8/31
Outline
Hungry
Dice
Example: Dice
Purpose and Model
New Elements
The Constructor
Rolling the Dice
The main function
Java Programming - L2. . .
9/31
Birthday Day
Outline
Hungry
Dice
Birthday Day
Purpose and Model
To model a set of dice, we must know how many there are and
how many sides they have. Context or input must supply the info.
The Dice constructor must store these numbers and allocate an
array of ints to represent the random numbers showing on
dice-tops.
in main:
Dice d = new Dice(5, 6);
d.roll();
d
count
sides
dice
5
6
5
Java Programming - L2. . .
in Dice constructor:
dice = new Int[count];
3
6
1
3
10/31
2
Outline
Hungry
Dice
New Elements
I
Private data members, public methods.
I
A constructor with parameters that initializes the data
members
I
this, used twice in the constructor
I
A default constructor
I
Math.random()
I
An accessor (getValue), used to print the results of roll()
I
A toString() method
I
An array of objects, in main(), allocated in a for loop
I
Calling class methods from within the class
Java Programming - L2. . .
11/31
Birthday Day
Outline
Hungry
Dice
Birthday Day
Class Skeleton
import java.util.*;
public class Die {
private int faces; // Number of sides on the die.
private int value; // The face that is showing.
Die ( int faces ) { ... }
Die ( ) { ... }
public int roll(){ ... }
public int getValue(){ return value; }
public String toString(){ ... }
public static void main( String[] args ) { ... }
}
Java Programming - L2. . .
12/31
Outline
Hungry
Dice
Birthday Day
The Dice Constructors
I
I
I
I
I
No part of this object can be initialized in the class
declaration because everything depends on user input.
This constructor has two parameters. I chose to give the
parameters the same names as the class members, creating an
ambiguity (one name, two different meanings).
I use this. when I want to refer to the data member, and
omit it to refer to the parameter. You DO NOT need “this”
unless there is ambiguity.
The parameters supply two integers that are stored in the two
int members.
Then the third data member is initialized using the first
parameter to allocate array space.
dice = new int[count];
Java Programming - L2. . .
13/31
Outline
Hungry
Dice
The Dice Constructors
// Constructor: initialize members.
Die ( int faces ) {
this.faces = faces;
value = roll();
System.out.println( this );
}
// Default constructor:
Die ( ) {
faces = 6;
value = roll();
}
Java Programming - L2. . .
14/31
Birthday Day
Outline
Hungry
Dice
Birthday Day
Rolling the Dice: Random Numbers
I
Java supplies two random number generators: a simple one,
and a better kind that is much more complex. We will use the
simple one in the Math class.
I
Math.random() returns a real number, approximately
uniformly distributed between 0.0 amd 1.0.
I
Our dice values are random integers between 1 and N. Thus,
we need to convert the real to an int in the required range.
I
(Math.random()*N) gives a real in the range 0 <= real < N.
I
(Math.random()*N) +1 shifts that range to
1 <= real < N + 1
I
Casting the result to type int discards the fractional part and
converts the value to an integer in range 1 <= int <= N.
Java Programming - L2. . .
15/31
Outline
Hungry
Dice
Birthday Day
The Class Methods
// Post: return is between 1 and faces.
public int roll(){
value = (int)(Math.random() * faces) + 1;
return value;
}
public int getValue(){
return value; }
public String toString(){
return "faces: " +faces +", value: " +value ;
}
Java Programming - L2. . .
16/31
Outline
Hungry
Dice
Birthday Day
The Class Methods
I
In the output, we want to see the dice displayed two ways.
I
The toString() method defines a format that shows all the
data members.
I
When you write a toString() method, include words to
explain the output, and include all of the data members of the
class. You NEED this information to debug.
I
The getValue() method is needed to provide the other
display format: just the random values of the four dice.
I
This program does not need a getValue() method because it
is never printed by itself.
Java Programming - L2. . .
17/31
Outline
Hungry
Dice
Birthday Day
The Main Function
I
main() announces that the program is running, then interacts
with the user until it collects enough information to call the
Dice constructor: Dice d = new Dice(count, sides);
I
This function uses an easy and lazy method of validation. If a
number is too small (or large) to be a legal input, it is simply
set to the smallest (or largest) legal value.
I
When the dice are ready to use, we call a method in the Dice
class to use them: d.roll;
I
The roll function calculates and prints a single set of random
values. That is all the program does.
I
The loop variable, k, is declared inside the loop because it is
only used in the loop.
Java Programming - L2. . .
18/31
Outline
Hungry
Dice
Birthday Day
public static void main( String[] args ) {
int nSides;
Die[] dice = new Die[4];
Scanner sc = new Scanner( System.in );
System.out.println("Roll Four Dice");
System.out.print("How many sides do your dice have?");
nSides = sc.nextInt();
for( int k=0; k<4; ++k) dice[k] = new Die(nSides);
System.out.println ( "Your dice have been rolled:" );
for( int k=0; k<4; ++k) {
dice[k].roll();
System.out.print (dice[k].getValue() + " ");
}
System.out.println();
}
Java Programming - L2. . .
19/31
Outline
Hungry
Dice
Example: Birthday Day
Purpose and Model
The Constructor
Rolling the Dice
The main function
Java Programming - L2. . .
20/31
Birthday Day
Outline
Hungry
Dice
Birthday Day
Purpose and Model
Given your birth month and date, calculate and print the day of
the week for your birthday.
New elements:
I
A private “helper” method.
I
The constructor calls a helper function as part of the
initialization
I
Public static final arrays of constants
I
String.equals() used to search an array of strings
I
Paradigm with break to implement the search loop
I
Calculating a subscript
I
The for-all loop
Java Programming - L2. . .
21/31
Outline
Hungry
Dice
Birthday Day
Class Skeleton
public class Birthday {
public static final String[]
private String month;
private int date;
private String day;
months,
// 3-letter abbreviation.
// Will be 1..31
// The day of the week.
Birthday( String m, int d){ ... }
private void calculateDay() { ... }
public String getday(){ return day;
public String toString(){ ... }
public static
void
}
main( String[] args ) { ... }
}
Java Programming - L2. . .
days, startsOn;
22/31
Outline
Hungry
Dice
Birthday Day
The Arrays of Constants
This class uses three arrays of constants (strings and integers).
public static final String[] months = {"Jan", "Feb",
"Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec" };
public static final String[] days = { "Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday" };
public static final int[] startsOn =
{4, 0, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2, };
I
I
I
I
These constants are all declared public static final.
“final” because they never change.
“static” means they are allocated and initialized at load time.
“public” because, being final, there is no harm in being visible.
Java Programming - L2. . .
23/31
Outline
Hungry
Dice
Birthday Day
The Birthday Constructor and toString
Birthday( String m, int d) {
month = m;
date = d;
calculateDay();
}
Only two of the data members are initialized directly from the
parameters. The third is initialized by a helper method, using the
data from the first two.
toString formats the class data members for output.
public String toString(){
return month +" " + date ;
}
Java Programming - L2. . .
24/31
Outline
Hungry
Dice
Birthday Day
The Helper Method
I
I
I
I
I
I
String.equals() returns true if this string is the same as
the parameter-string. Be sure that the String on the left is
not null.
The loop implements the easiest way to search an array. The
loop variable, k, must be declared outside the loop because it
is used after the loop exit.
When control leaves the loop, the value of k is either larger
than the array length or equal to the subscript where the
target string was found. We use a conditional to handle the
two possibilities.
The birthday day depends on the day on which the month
starts. These days are stored in the startsOn array.
We use %7 because there are 7 days in each week.
We use the answer to initialize the third class member.
Java Programming - L2. . .
25/31
Outline
Hungry
Dice
Birthday Day
The Helper Method
private void calculateDay() {
int found, k, answer;
for(k=0; k<12; ++k) {
if (month.equals(months[k])) break;
}
found = k;
if (found == 12)
System.out.println("Your month name was not....");
else {
answer = (startsOn[k] + date -1)%7;
day = days[answer];
}
}
Java Programming - L2. . .
26/31
Outline
Hungry
Dice
Birthday Day
The beginning of main()
I
main prints a heading to show the user that it is running.
I
A for-all loop is then used to print the abbreviations for the
months. This loop can be used with any array where you want
to process every array slot and you do not need to know the
subscript of anything.
I
Inside the parentheses, write the base type of the array, a
short variable name, and the array name:
for( String s : months) ...
I
This means that the body of the loop will be done for every
String in the array named months.
I
Inside the loop, the name s is used to refer to the String in
the current slot of the array.
Java Programming - L2. . .
27/31
Outline
Hungry
Dice
Birthday Day
The beginning of main()
public static void main( String[] args ) {
int date;
String monthname;
Scanner sc = new Scanner( System.in );
System.out.println("\nBirthday Calculator, Welcome!");
System.out.print ("Months are: ");
for( String s : months) System.out.print( s+" " );
...
Java Programming - L2. . .
28/31
Outline
Hungry
Dice
Birthday Day
The end of main()
I
After printing headings, main gets the user’s input for birth
month and date.
I
The method String.next() reads the next whitespace
delimited string in the input.
I
In this program, ALL of the work is done in the constructor.
This is not unusual for very small programs. After creating a
Birthday object, main prints it’s information and is done.
I
After construction, the toString() method is used to
echo-print the input, and getDay() is needed to print the
answer.
Java Programming - L2. . .
29/31
Outline
Hungry
Dice
Birthday Day
The end of main()
...
System.out.println("\n\nEnter birth month and date:");
monthname = sc.next();
date = sc.nextInt();
Birthday b = new Birthday (monthname, date);
System.out.printf ( "Your %s birthday is on %s
this year\n\n", b.toString(), b.getDay() );
}
Java Programming - L2. . .
30/31
Outline
Hungry
Dice
Homework
Program 2: Modify the Birthday Program.
Start with the Birthday program.
Modify it to also print out the day of the year that the birthday
falls on.
Detailed instructions are given on the website.
Java Programming - L2. . .
31/31
Birthday Day