java programming code examples for week 2eliza.newhaven.edu/java/attach/l2example.pdfoutline...

31
Outline Hungry Dice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January 29 and Feb 3 2015 Java Programming - L2. . . 1/31

Upload: dongoc

Post on 27-Mar-2018

224 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

Java ProgrammingCode Examples for Week 2

Alice E. Fischer

January 29 and Feb 3 2015

Java Programming - L2. . . 1/31

Page 2: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

HungryIn-class Exercise

Dice

Birthday DayHomework

Java Programming - L2. . . 2/31

Page 3: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

Example: Hungry

Purpose and new elementsCode

Output

Java Programming - L2. . . 3/31

Page 4: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

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 andexecutes 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

Page 5: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

Class Skeleton

import java.util.Scanner;

public class Hungry {

final int full = 17; // Demand 17 jellybeans.

int level = 0; // 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

Page 6: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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

Page 7: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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

Page 8: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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

Page 9: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

Example: Dice

Purpose and ModelNew Elements

The ConstructorRolling the Dice

The main function

Java Programming - L2. . . 9/31

Page 10: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

Purpose and ModelTo model a set of dice, we must know how many there are andhow many sides they have. Context or input must supply the info.

The Dice constructor must store these numbers and allocate anarray of ints to represent the random numbers showing ondice-tops.

in Dice constructor:dice = new Int[count];

in main:Dice d = new Dice(5, 6);d.roll();

5d6

1 23 6 3

countsidesdice

5

Java Programming - L2. . . 10/31

Page 11: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

New Elements

I Private data members, public methods.

I A constructor with parameters that initializes the datamembers

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

Page 12: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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

Page 13: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

The Dice Constructors

I No part of this object can be initialized in the classdeclaration because everything depends on user input.

I This constructor has two parameters. I chose to give theparameters the same names as the class members, creating anambiguity (one name, two different meanings).

I I use this. when I want to refer to the data member, andomit it to refer to the parameter. You DO NOT need “this”unless there is ambiguity.

I The parameters supply two integers that are stored in the twoint members.

I Then the third data member is initialized using the firstparameter to allocate array space.dice = new int[count];

Java Programming - L2. . . 13/31

Page 14: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

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

Page 15: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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 thesimple one in the Math class.

I Math.random() returns a real number, approximatelyuniformly 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 to1 <= real < N + 1

I Casting the result to type int discards the fractional part andconverts the value to an integer in range 1 <= int <= N.

Java Programming - L2. . . 15/31

Page 16: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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

Page 17: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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 thedata members.

I When you write a toString() method, include words toexplain the output, and include all of the data members of theclass. You NEED this information to debug.

I The getValue() method is needed to provide the otherdisplay format: just the random values of the four dice.

I This program does not need a getValue() method because itis never printed by itself.

Java Programming - L2. . . 17/31

Page 18: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

The Main Function

I main() announces that the program is running, then interactswith the user until it collects enough information to call theDice constructor: Dice d = new Dice(count, sides);

I This function uses an easy and lazy method of validation. If anumber is too small (or large) to be a legal input, it is simplyset to the smallest (or largest) legal value.

I When the dice are ready to use, we call a method in the Diceclass to use them: d.roll;

I The roll function calculates and prints a single set of randomvalues. That is all the program does.

I The loop variable, k, is declared inside the loop because it isonly used in the loop.

Java Programming - L2. . . 18/31

Page 19: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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

Page 20: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

Example: Birthday Day

Purpose and ModelThe ConstructorRolling the Dice

The main function

Java Programming - L2. . . 20/31

Page 21: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

Purpose and Model

Given your birth month and date, calculate and print the day ofthe week for your birthday.

New elements:

I A private “helper” method.

I The constructor calls a helper function as part of theinitialization

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

Page 22: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

Class Skeleton

public class Birthday {

public static final String[] months, days, startsOn;

private String month; // 3-letter abbreviation.

private int date; // Will be 1..31

private String day; // 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. . . 22/31

Page 23: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

The Arrays of ConstantsThis 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 These constants are all declared public static final.I “final” because they never change.I “static” means they are allocated and initialized at load time.I “public” because, being final, there is no harm in being visible.

Java Programming - L2. . . 23/31

Page 24: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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 theparameters. The third is initialized by a helper method, using thedata from the first two.

toString formats the class data members for output.

public String toString(){

return month +" " + date ;

}

Java Programming - L2. . . 24/31

Page 25: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

The Helper MethodI String.equals() returns true if this string is the same as

the parameter-string. Be sure that the String on the left isnot null.

I The loop implements the easiest way to search an array. Theloop variable, k, must be declared outside the loop because itis used after the loop exit.

I When control leaves the loop, the value of k is either largerthan the array length or equal to the subscript where thetarget string was found. We use a conditional to handle thetwo possibilities.

I The birthday day depends on the day on which the monthstarts. These days are stored in the startsOn array.

I We use %7 because there are 7 days in each week.I We use the answer to initialize the third class member.

Java Programming - L2. . . 25/31

Page 26: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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

Page 27: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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 themonths. This loop can be used with any array where you wantto process every array slot and you do not need to know thesubscript of anything.

I Inside the parentheses, write the base type of the array, ashort variable name, and the array name:

for( String s : months) ...

I This means that the body of the loop will be done for everyString in the array named months.

I Inside the loop, the name s is used to refer to the String inthe current slot of the array.

Java Programming - L2. . . 27/31

Page 28: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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

Page 29: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

The end of main()

I After printing headings, main gets the user’s input for birthmonth and date.

I The method String.next() reads the next whitespacedelimited 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 aBirthday object, main prints it’s information and is done.

I After construction, the toString() method is used toecho-print the input, and getDay() is needed to print theanswer.

Java Programming - L2. . . 29/31

Page 30: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

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

Page 31: Java Programming Code Examples for Week 2eliza.newhaven.edu/java/attach/L2Example.pdfOutline HungryDice Birthday Day Java Programming Code Examples for Week 2 Alice E. Fischer January

Outline Hungry Dice Birthday Day

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 birthdayfalls on.

Detailed instructions are given on the website.

Java Programming - L2. . . 31/31