+ All Categories
Home > Documents > 1 Today’s Objectives Announcements Hand in your Ethics Paper Less than 1 week left to earn bonus...

1 Today’s Objectives Announcements Hand in your Ethics Paper Less than 1 week left to earn bonus...

Date post: 28-Dec-2015
Category:
Upload: marjory-bell
View: 215 times
Download: 0 times
Share this document with a friend
62
1 Today’s Objectives Announcements Hand in your Ethics Paper Less than 1 week left to earn bonus points with the Feedback Mechanism Complete the Feedback Mechanism before 7-Feb, 1 p.m. Complete the assessment quiz Complete the survey questions If you have problems, contact 281-283-2982 or [email protected] Quiz 1 Basic Java Programming Java API – http://java.sun.com/j2se/1.5.0/docs/api/ More basics Arrays Using java.util.ArrayList Using java.util.Stack Abstract Data Types (ADT) Bonus Lab 2 – reading a data file, adding objects to an array Week 3
Transcript

1

Today’s Objectives

Announcements• Hand in your Ethics Paper• Less than 1 week left to earn bonus points with the Feedback Mechanism

– Complete the Feedback Mechanism before 7-Feb, 1 p.m.– Complete the assessment quiz– Complete the survey questions

– If you have problems, contact 281-283-2982 or [email protected]

Quiz 1 Basic Java Programming

• Java API – http://java.sun.com/j2se/1.5.0/docs/api/ • More basics• Arrays• Using java.util.ArrayList• Using java.util.Stack

Abstract Data Types (ADT) Bonus Lab 2 – reading a data file, adding objects to an array

Week 3

Quiz #1

Closed book and closed notes

15 minutesPlease clear your desks, including cell phones,

remove any headset or ear phone, and log off from the computer

Basic Java Programming

Operators, equals, and toString

4

Operators and Expressions

An expression — combining variables and literals with operators to create a new valueExample:double x, y = 10.0;x = y / 4.0;

Basic Java Programming (Goodrich, 20–24)

variables literaloperators

Binary arithmetic operators+ addition- subtraction* multiplication/ division% modulo (finds the remainder)

5

Integer Division

The remainder is treated differently

Division operatorint m, n = 11;m = n / 5;System.out.println("m = " + m); //What prints?

Modulo operatorint m, n = 11;m = n % 5;System.out.println("m = " + m); //What prints?

Basic Java Programming (Goodrich, 20–24)

equals, toString and UML

(From last week’s slides)

Implementing the Deck class in our case study

8

Implementing Deck

package edu.uhcl.sce.simplesolitaire;

public class Deck{ private Card[] cards;

}

Since a real deck has 52 cards, the Simple Solitaire Deck object must store 52 Card objects.

We can use an array as one of the instance variables in the Deck class and store all 52 Card objects in it.

Basic Java Programming (Flanagan; Drake)

Declaration of the array instance variable

9

Array

Collection of elements of the same data type, stored in adjacent memory locations

Creating an arrayint[] myArray; //variable declared, not initializedmyArray = new int[5]; //memory allocated for array A number that specifies the capacity is required

Initializing an array• Array elements are initialized to their default values when memory

for the array is allocated• An array can be allocated and initialized in the same statement

int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17};

Basic Java Programming (Goodrich, 34; Flanagan, 76–77)

10

Using Arrays

The first element in every array has the index 0

Each element can be accessed by using its indexint[] myArray = new int[5];myArray[0] = 42;System.out.println(myArray[0]);//what prints?System.out.println(myArray[3]);//what prints?

Every array has a public instance variable named length

Printing the array elementsfor( int i=0; i<myArray.length; ++i ) System.out.println(myArray[i]);

Basic Java Programming (Goodrich, 34–38; Flanagan, 76)

11

Array Bounds

The compiler does not check array boundsint[] myArray = new int[5];System.out.println(myArray[256]); //will compile

But every access is checked at runtime, and if the index is out of bounds then the output is “undefined” and the error, ArrayIndexOutOfBoundsException is thrown

Common error:

int[] a = new int[5];System.out.print( a[5] );

Basic Java Programming (Goodrich, 34–38; Flanagan, 76)

12

Arrays can store eitherprimitive values or objects

Storing primitive variables in an arrayint[] myArray = new int[5];myArray[0] = 42;System.out.println(myArray[0]);//what prints?

Storing reference variables in an arrayCard[] cards = new Card[52];Card aceOfSpades = new Card(Card.ACE,Card.SPADES);cards[0] = aceOfSpades;

Basic Java Programming (Goodrich, 96–100)

13

Arrays can store eitherprimitive values or objects

Storing primitive variables in an arrayint[] myArray = new int[5];myArray[0] = 42;System.out.println(myArray[0]);//what prints?

Storing reference variables in an arrayCard[] cards = new Card[52];Card aceOfSpades = new Card(Card.ACE,Card.SPADES);cards[0] = aceOfSpades;cards[1] = new Card(2,Card.SPADES);

Basic Java Programming (Goodrich, 96–100)

An anonymous object

14

Arrays can store eitherprimitive values or objects

Storing primitive variables in an arrayint[] myArray = new int[5];myArray[0] = 42;System.out.println(myArray[0]);//what prints?

Storing reference variables in an arrayCard[] cards = new Card[52];Card aceOfSpades = new Card(Card.ACE,Card.SPADES);cards[0] = aceOfSpades;cards[1] = new Card(2,Card.SPADES);System.out.println(cards[0].toString()); //what prints?System.out.println(cards[1]); //what prints?

Basic Java Programming (Goodrich, 96–100)

An anonymous object

15

Implementing Deck

package edu.uhcl.sce.simplesolitaire;

public class Deck{ private Card[] cards;

public Deck(){ cards = new Card[52];

for (int suit=Card.SPADES; suit<=Card.CLUBS; suit++){ for(int rank=Card.ACE; rank<=Card.KING; rank++){ cards[size] = new Card(rank,suit);

} } }

}

The constructor’s job is to initialize all instance variables, so the Deck constructor must initialize the array that holds the Card objects.

Basic Java Programming (Flanagan; Drake)

Memory allocated for the array

Nested “for” loops are used to instantiate the correct Card objects and store them in the array

Now, whenever a Deck object is instantiated, the data for Simple Solitaire (the cards) will be organized in memory by storing it in the “cards” array. This array is this class’s data structure.

//from the Card class public static final int SPADES = 0; public static final int HEARTS = 1; public static final int DIAMONDS = 2; public static final int CLUBS = 3; public static final int ACE = 1; public static final int JACK = 11; public static final int QUEEN = 12; public static final int KING = 13;}

//from the Card class public static final int SPADES = 0; public static final int HEARTS = 1; public static final int DIAMONDS = 2; public static final int CLUBS = 3; public static final int ACE = 1; public static final int JACK = 11; public static final int QUEEN = 12; public static final int KING = 13;}

16

Implementing Deck

package edu.uhcl.sce.simplesolitaire;

public class Deck{ private Card[] cards; private int size; public Deck(){ cards = new Card[52]; size = 0; for (int suit=Card.SPADES; suit<=Card.CLUBS; suit++){ for(int rank=Card.ACE; rank<=Card.KING; rank++){ cards[size] = new Card(rank,suit); size += 1; } } } public boolean isEmpty(){ return size == 0; } public int size(){ return size; }

}

One of the requirements states that in each turn we must “deal four cards.”

To “deal” a Card object, we simply remove it from the deck and display it to the player with toString.

Instance variable named “size”• increment size in the constructor each

time a Card object is added to the array• decrement size to remove a Card

object from the deck• test size to see if there are no Card

objects left

Since size is private, we need to add two public methods, isEmpty() and size(), to access the size data in other parts of the program.

Basic Java Programming (Flanagan; Drake)

17

Implementing Deck

package edu.uhcl.sce.simplesolitaire;

public class Deck{ private Card[] cards; private int size; public Deck(){ cards = new Card[52]; size = 0; for (int suit=Card.SPADES; suit<=Card.CLUBS; suit++){ for(int rank=Card.ACE; rank<=Card.KING; rank++){ cards[size] = new Card(rank,suit); size += 1; } } } public boolean isEmpty(){ return size == 0; } public int size(){ return size; } public Card deal(){ size--; return cards[size]; }}

Now we can implement the deal() method.

The value in size is always equal to the index of the next available array location.

We can remove a Card object from the deck by decrementing size and returning the Card object at the “end” of the array.

Basic Java Programming (Flanagan; Drake)

The part of our program that called the deal method gets the returned Card object and displays it to the player with its toString method.

Ks 9h 3d Ac

cards.size == 4

cards0 1 2 3 4

18

Disadvantage of Using Arrays

An Array object cannot be resized

Basic Java Programming (Naftalin, 224)

19

ArrayLists and Arrays

A Java ArrayList object can be used instead of a Java Array

The ArrayList is considered to be a “better array”• Both store elements in a linear sequence• Both provide access to elements by their “index”

The ArrayList will automatically grow, adding more memory space for itself whenever it’s needed

Basic Java Programming (Goodrich, 222–230)

20

Using the java.util.ArrayList

You need to import the libraryimport java.util.ArrayList;

You need to know how to instantiate an ArrayList objectprivate ArrayList<Card> cards;

cards = new ArrayList<Card>();

You need to know some of the operationsint size()boolean isEmpty()E add(E element)E get(int index) E set(int index, E element)E remove(int index)

Basic Java Programming (Goodrich, 159)

Name of the class Type of data to be stored in it

Refers to any data type

Allocate the memory

Declare a reference variableUse access

specifier only whenthis is an instance variable

21

Implementing Deck

package edu.uhcl.sce.simplesolitaire;import java.util.ArrayList;

public class Deck{ private ArrayList<Card> cards; public Deck(){ cards = new ArrayList<Card>(); for (int suit=Card.SPADES; suit<=Card.CLUBS; suit++){ for(int rank=Card.ACE; rank<=Card.KING; rank++){ cards.add(new Card(rank,suit)); } } } public boolean isEmpty(){ return cards.isEmpty(); } public int size(){ return cards.size(); } public Card deal(){ return cards.remove(cards.size() – 1); }}

We can use an ArrayList to hold data in the Deck instead of an Array.

Since the cards instance variable is private, we can change it without breaking any other part of our program.

(However, we still need to be careful not to change any of the public interface part of our program.)

Basic Java Programming (Flanagan; Drake)

These methods can be implemented by simply calling the corresponding method in the ArrayList

22

Implementing DeckBasic Java Programming (Flanagan; Drake)

If we use an ArrayList to store the Deck’s data, then the ArrayList is now this class’s data structure, right?

package edu.uhcl.sce.simplesolitaire;import java.util.ArrayList;

public class Deck{ private ArrayList<Card> cards; public Deck(){ cards = new ArrayList<Card>(); for (int suit=Card.SPADES; suit<=Card.CLUBS; suit++){ for(int rank=Card.ACE; rank<=Card.KING; rank++){ cards.add(new Card(rank,suit)); } } } public boolean isEmpty(){ return cards.isEmpty(); } public int size(){ return cards.size(); } public Card deal(){ return cards.remove(cards.size() – 1); }}

23

Implementing DeckBasic Java Programming (Flanagan; Drake)

If we use an ArrayList to store the Deck’s data, then the ArrayList is now this class’s data structure, right?

Right! The ArrayList is a data structure that’s used frequently in Java programs.

package edu.uhcl.sce.simplesolitaire;import java.util.ArrayList;

public class Deck{ private ArrayList<Card> cards; public Deck(){ cards = new ArrayList<Card>(); for (int suit=Card.SPADES; suit<=Card.CLUBS; suit++){ for(int rank=Card.ACE; rank<=Card.KING; rank++){ cards.add(new Card(rank,suit)); } } } public boolean isEmpty(){ return cards.isEmpty(); } public int size(){ return cards.size(); } public Card deal(){ return cards.remove(cards.size() – 1); }}

24

An ArrayList is specified by an ADT

Abstract Data Type (ADT)• A specification for a data structure that tells us

– The type of data stored– The operations that are supported

• Specifies what the operations do, but not how they do it• An ADT for an ArrayList is on page 222 in the textbook

int size()boolean isEmpty()void add( i, E )E get( i )void set( i, E )void remove( i )

The concrete implementation of an ADT is a class– Makes it easy to encapsulate data + operations– Specifies how to store the data– Specifies how the operations work

Objects and Classes (Goodrich, 60, 222)

25

Storing Data in ArrayLists

A Java ArrayList can only store objects, not primitive variables

Normally, we store values like integers, real numbers, or boolean values in primitive variables

But if we want to store these simple values as objects in Java, then we need to use a wrapper class

Basic Java Programming (Goodrich, 222–230)

26

Wrapper Classes

Each primitive data type has a “wrapper” classPrimitive data type Wrapper class

boolean Booleanchar Characterbyte Byteint Integerlong Longshort Shortfloat Floatdouble Double

Basic Java Programming (Goodrich, 8)

27

Objects from Wrapper Classes

An object is created using new new allocates memory to store an object, then

returns a reference to that memory

public class Main { public static void main (String args[]) { Integer n; //n is declared but no memory allocated n = new Integer(1024); //creates a new object and

//stores 1024 in memory Integer m = new Integer(64); String s = new String("Test"); Greeting hello = new Greeting("Hello"); }}

Basic Java Programming (Goodrich, 7)

28

Storing Data in an ArrayList

1. Create the ArrayList object2. Create an object to store in it and then use add()

import java.util.ArrayList;public class Main { public static void main (String args[]) {

ArrayList<Character> charList = new ArrayList<Character>(); Character first = new Character('a'); charList.add(first);

}}

Basic Java Programming (Goodrich, 222–230)

Instantiate an objectAdd it to the ArrayList

29

Storing Data in an ArrayList

1. Create the ArrayList object2. Create an object to store in it and then use add()

import java.util.ArrayList;public class Main { public static void main (String args[]) {

ArrayList<Character> charList = new ArrayList<Character>(); Character first = new Character('a'); charList.add(first); charList.add(new Character('b'));

}}

Basic Java Programming (Goodrich, 222–230)

Instantiate an object and add it to the ArrayList in one operation

30

Storing Data in an ArrayList

1. Create the ArrayList object2. Create an object to store in it and then use add()

import java.util.ArrayList;public class Main { public static void main (String args[]) {

ArrayList<Character> charList = new ArrayList<Character>(); Character first = new Character('a'); charList.add(first); charList.add(new Character('b')); charList.add('c'); }}

Basic Java Programming (Goodrich, 222–230; Naftalin, 7)

Instantiate an object and add it to the ArrayList in one operation using boxing – automatic conversion of a primitive type to the corresponding wrapper type

31

Static Wrapper Class Methods

Wrapper classes have static methodsWrapper class Some examples of its static methods

Character public static boolean isLetter(char ch)public static char toUpperCase(char ch)

Usage:String s1 = "Go dog";

char c = s1.charAt(0); if (Character.isLetter(c))

System.out.println(c + " is a letter");

Integer public static int parseInt(String s)Usage:String s2 = "42";

int n = 0;try{ n = Integer.parseInt(s2);

} catch (NumberFormatException e){ System.out.println(e.message()); }

Basic Java Programming (Goodrich, 8)

32

Implementing Deck

package edu.uhcl.sce.simplesolitaire;import java.util.ArrayList;

public class Deck{ private ArrayList<Card> cards; public Deck(){ cards = new ArrayList<Card>(); for (int suit=Card.SPADES; suit<=Card.CLUBS; suit++){ for(int rank=Card.ACE; rank<=Card.KING; rank++){ cards.add(new Card(rank,suit)); } } } public boolean isEmpty(){ return cards.isEmpty(); } public int size(){ return cards.size(); } public Card deal(){ return cards.remove(cards.size() – 1); }

public void shuffle(){ }}

The requirements state that we must “shuffle the deck” in the beginning before we can deal any cards.

In object-oriented programming, we just tell the Deck object to shuffle itself.

So we need to add a shuffle() method to the Deck class so that our program can tell its Deck object to “shuffle” before it “deals.”

Basic Java Programming (Flanagan; Drake)

Is there a “shuffle” method that we can use with the ArrayList?

Implementing the SimpleSolitaire class in our case study

34

Implementing SimpleSolitaire

package edu.uhcl.sce.simplesolitaire;

public class SimpleSolitaire{ private Deck deck;

SimpleSolitaire(){ deck = new Deck(); deck.shuffle();

}

}

This class represents the game itself.

Since the game is played with a deck of cards, we need a Deck object as one of the game’s instance variables.

Basic Java Programming (Flanagan; Drake)

Declare a Deck object as an instance variable

In the constructor, we allocate memory for the deck and call its “shuffle” method.

35

The Game Loop

All computer games use a “game loop” to run the game

The game loop is a continuous loop that controls the steps in the game, including drawing the image or text output on the screen

A while loop can be used as a simple game loop

Basic Java Programming (LaMothe, 16; Morrison, 32)

36

Looping with while

public class Main { public static void main (String args[]) { boolean done = false; try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while( !done ) { System.out.println("Exit program? (Y/N): "); String temp = br.readLine(); char input = temp.charAt(0); switch ( input ) { case 'Y' : case 'y' : done = true; System.out.println("Bye"); break; default : break; } } } catch(Exception e){ System.out.println("ERROR"); }}

Basic Java Programming (Goodrich, 29)

37

Looping with while

public class Main { public static void main (String args[]) { boolean done = false; try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while( !done ) { System.out.println("Exit program? (Y/N): "); String temp = br.readLine(); char input = temp.charAt(0); switch ( input ) { case 'Y' : case 'y' : done = true; System.out.println("Bye"); break; default : break; } } } catch(Exception e){ System.out.println("ERROR"); }}

Basic Java Programming (Goodrich, 29)

Keyword “while” is followed by a condition that evaluates to either true or false

38

Looping with while

public class Main { public static void main (String args[]) { boolean done = false; try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while( !done ) { System.out.println("Exit program? (Y/N): "); String temp = br.readLine(); char input = temp.charAt(0); switch ( input ) { case 'Y' : case 'y' : done = true; System.out.println("Bye"); break; default : break; } } } catch(Exception e){ System.out.println("ERROR"); }}

Basic Java Programming (Goodrich, 29)

Keyword “while” is followed by a condition that evaluates to either true or false

If the condition is true, then one iteration of the loop is executed, and the condition is tested again

39

Looping with while

public class Main { public static void main (String args[]) { boolean done = false; try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while( !done ) { System.out.println("Exit program? (Y/N): "); String temp = br.readLine(); char input = temp.charAt(0); switch ( input ) { case 'Y' : case 'y' : done = true; System.out.println("Bye"); break; default : break; } } } catch(Exception e){ System.out.println("ERROR"); }}

Basic Java Programming (Goodrich, 29)

Keyword “while” is followed by a condition that evaluates to either true or false

If the condition is true, then one iteration of the loop is executed, and the condition is tested again

To stop the next iteration, change the condition so that it evaluates to false, then break

40

switch Structure

Can replace a complicated if/else structure

switch( grade ){ case 'A': case 'a': aCount++; break; case 'B': case 'b': bCount++; break; default: System.out.println("Incorrect input"); break;}

Basic Java Programming (Deitel, 199–205,Goodrich, 28)

This controlling expression is compared to each of the case labels

Execution continues at the case label that matches

The break causes execution to go to the next line following the switch

41

Implementing SimpleSolitaire

ALGORITHM play() shuffle the deck deal four cards

Before we can code a game loop, we need to iterate back to the design stage and write an algorithm to describe how the game should be played.

Basic Java Programming (Flanagan; Drake)

• Simple solitaire is a card game played by one person

• Use a regular deck of playing cards

• Goal is to discard all of the cards• Shuffle the deck, then deal four

cards1. If two cards have the same rank,

discard both2. If two cards have the same suit,

discard the lower rank card3. Deal four more cards

RequirementsStart with the requirements

Assuming that the SimpleSolitaire class will have a play method that contains the game loop, we can write an algorithm for it. Try to imagine how the game would be played with a real deck of cards.

42

Implementing SimpleSolitaire

ALGORITHM play() shuffle the deck deal four cards

Before we can code a game loop, we need to iterate back to the design stage and write an algorithm to describe how the game should be played.

Basic Java Programming (Flanagan; Drake)

• Simple solitaire is a card game played by one person

• Use a regular deck of playing cards

• Goal is to discard all of the cards• Shuffle the deck, then deal four

cards1. If two cards have the same rank,

discard both2. If two cards have the same suit,

discard the lower rank card3. Deal four more cards

RequirementsStart with the requirements

Assuming that the SimpleSolitaire class will have a play method that contains the game loop, we can write an algorithm for it. Try to imagine how the game would be played with a real deck of cards.

43

Implementing SimpleSolitaire

ALGORITHM play() shuffle the deck deal four cards

Before we can code a game loop, we need to iterate back to the design stage and write an algorithm to describe how the game should be played.

Basic Java Programming (Flanagan; Drake)

• Simple solitaire is a card game played by one person

• Use a regular deck of playing cards

• Goal is to discard all of the cards• Shuffle the deck, then deal four

cards1. If two cards have the same rank,

discard both2. If two cards have the same suit,

discard the lower rank card3. Deal four more cards

RequirementsStart with the requirements

Assuming that the SimpleSolitaire class will have a play method that contains the game loop, we can write an algorithm for it. Try to imagine how the game would be played with a real deck of cards.

We’ll need some way to store these four objects

44

Implementing SimpleSolitaire

ALGORITHM play() shuffle the deck deal four cards

Before we can code a game loop, we need to iterate back to the design stage and write an algorithm to describe how the game should be played.

Basic Java Programming (Flanagan; Drake)

• Simple solitaire is a card game played by one person

• Use a regular deck of playing cards

• Goal is to discard all of the cards• Shuffle the deck, then deal four

cards1. If two cards have the same rank,

discard both2. If two cards have the same suit,

discard the lower rank card3. Deal four more cards

RequirementsStart with the requirements

Assuming that the SimpleSolitaire class will have a play method that contains the game loop, we can write an algorithm for it. Try to imagine how the game would be played with a real deck of cards.

We’ll need some way to store these four objects

while not done print the four cards if there are cards left, we're not done else we're done, so stop get the next move from the user if the move is "pair" removePair() else if the move is "suit" removeLowCard() else if the move is "deal" dealFourCards() else stop

45

Implementing SimpleSolitaire

ALGORITHM play() shuffle the deck deal four cards

Before we can code a game loop, we need to iterate back to the design stage and write an algorithm to describe how the game should be played.

Basic Java Programming (Flanagan; Drake)

• Simple solitaire is a card game played by one person

• Use a regular deck of playing cards

• Goal is to discard all of the cards• Shuffle the deck, then deal four

cards1. If two cards have the same rank,

discard both2. If two cards have the same suit,

discard the lower rank card3. Deal four more cards

RequirementsStart with the requirements

Assuming that the SimpleSolitaire class will have a play method that contains the game loop, we can write an algorithm for it. Try to imagine how the game would be played with a real deck of cards.

We’ll need a method for each action specified in the play description

We’ll need some way to store these four objects

while not done print the four cards if there are cards left, we're not done else we're done, so stop get the next move from the user if the move is "pair" removePair() else if the move is "suit" removeLowCard() else if the move is "deal" dealFourCards() else stop

46

Implementing SimpleSolitaire

package edu.uhcl.sce.simplesolitaire;

public class SimpleSolitaire{ private Deck deck;

SimpleSolitaire(){ deck = new Deck(); deck.shuffle();

}

}

Our class has started well, but now we need a data structure that will store the four cards that are dealt from the deck

Basic Java Programming (Flanagan; Drake)

ALGORITHM play() shuffle the deck deal four cards

We’ll need some way to store these four objects

while not done print the four cards if there are cards left, we're not done else we're done, so stop get the next move from the user if the move is "pair" removePair() else if the move is "suit" removeLowCard() else if the move is "deal" dealFourCards() else stop

47

Deal 4 cardsBasic Java Programming

In “real life,” when we deal the cards, we lay them on the table in four stacks, so that only the top card is visible.

RankIn our game, we can simulate this behavior by using a stack data structure for each of the four “stacks” of cards.

48

java.util.Stack

Stack

+ Stack()+ push( e : E ) E+ pop() : E+ peek() : E+ empty() : boolean

Class name – top section

Methods – bottom section.

Using a java.util.Stack

'E' is a placeholder that represents any data type.

push – insert an element at the top of the stack

pop – remove an element from the top of the stack

peek – return the top element in the stack without removing it

empty - Returns true when the stack is empty, and returns false when it contains elements

ADT for java.util.Stack

49

Using the java.util.Stack

You need to know how to import the libraryimport java.util.Stack;

You need to know how to instantiate a Stack objectprivate Stack<Character> st;

st = new Stack<Character>();

You need to know the operationsE push( E element )E pop() E peek()boolean empty()

You don’t need to know how the stack was implemented

Using a java.util.Stack (Goodrich, 159)

Name of the class Type of data to be stored in it

Refers to any data type

Allocate the memory

Declare a reference variable

50

Implementing SimpleSolitaire

package edu.uhcl.sce.simplesolitaire;

public class SimpleSolitaire{ private Deck deck; private Stack<Card>[] stacks;

SimpleSolitaire(){ deck = new Deck(); deck.shuffle(); stacks = new Stack[4]; for (int i=0; i<4; ++i){ stacks[i] = new Stack<Card>(); } }

}

We’ll add an array of four stacks.

Each stack will hold one of the four cards that are dealt

Basic Java Programming (Flanagan; Drake)

ALGORITHM play() shuffle the deck deal four cards

We’ll need some way to store these four objects

while not done print the four cards if there are cards left, we're not done else we're done, so stop get the next move from the user if the move is "pair" removePair() else if the move is "suit" removeLowCard() else if the move is "deal" dealFourCards() else stop

Then allocate the memory for each stack in the constructor

Allocate the memory for the array

Using the java.util.Stack...

...in an algorithm and a program

52

Using a stack in an algorithmand a program

ALGORITHM reverseString(s)Input: a stringOutput: the string reversed

Stack stStringBuilder sb

Basic Java Programming (Goodrich, 159)

ADT for java.util.Stack

E push( E element ) E pop() E peek() boolean empty()

Tips for writing an algorithm

Use the correct data structureUse the correct ADT operationsUse object-oriented syntaxIndent clearlyUse a return statement at the end

Tips for writing an algorithm

Use the correct data structureUse the correct ADT operationsUse object-oriented syntaxIndent clearlyUse a return statement at the end

53

Using a stack in an algorithmand a program

ALGORITHM reverseString(s)Input: a stringOutput: the string reversed

Stack stStringBuilder sbfor i=0 to s1.length()-1 st.push(s.charAt(i))

Basic Java Programming (Goodrich, 159)

Tips for writing an algorithm

Use the correct data structureUse the correct ADT operationsUse object-oriented syntaxIndent clearlyUse a return statement at the end

Tips for writing an algorithm

Use the correct data structureUse the correct ADT operationsUse object-oriented syntaxIndent clearlyUse a return statement at the end

54

Using a stack in an algorithmand a program

ALGORITHM reverseString(s)Input: a stringOutput: the string reversed

Stack stStringBuilder sbfor i=0 to s1.length()-1 st.push(s.charAt(i))while not st.empty()

char c = st.pop() sb.append(c)

Basic Java Programming (Goodrich, 159)

Tips for writing an algorithm

Use the correct data structureUse the correct ADT operationsUse object-oriented syntaxIndent clearlyUse a return statement at the end

Tips for writing an algorithm

Use the correct data structureUse the correct ADT operationsUse object-oriented syntaxIndent clearlyUse a return statement at the end

55

Using a stack in an algorithmand a program

ALGORITHM reverseString(s)Input: a stringOutput: the string reversed

Stack stStringBuilder sbfor i=0 to s1.length()-1 st.push(s.charAt(i))while not st.empty()

char c = st.pop() sb.append(c)

return sb.toString()

Basic Java Programming (Goodrich, 159)

Tips for writing an algorithm

Use the correct data structureUse the correct ADT operationsUse object-oriented syntaxIndent clearlyUse a return statement at the end

Tips for writing an algorithm

Use the correct data structureUse the correct ADT operationsUse object-oriented syntaxIndent clearlyUse a return statement at the end

56

Using a stack in an algorithmand a program

Now we need to convert the algorithm to Java:

Basic Java Programming (Goodrich, 159)

ALGORITHM reverseString(s) Input: a string Output: the string reversed

Stack stStringBuilder sbfor i=0 to s1.length()-1 st.push(s.charAt(i))()while not st.empty ()char c = st.pop sb.append(c)()return sb.toString

ALGORITHMreverseString(s) Input: a string Output: the string reversed

Stack stStringBuilder sbfor i=0 to s1.length()-1 st.push(s.charAt(i))while not st.empty() char c = st.pop() sb.append(c)return sb.toString()

package edu.uhcl.sce.demostack;import java.util.Stack;

public class StringReverser{

private Stack<Character> st;

public String reverseString(String s){ StringBuilder sb = new StringBuilder(); for(int i=0; i<s.length(); ++i){ st.push(s.charAt(i)); } while(!st.empty()){ char c = st.pop(); sb.append(c); } return sb.toString(); }

}

We need a java.util.stack object

We need a reverseString method

If our algorithm is good, the method implementation should be easy.

What additional method is needed for initializing the instance variable?

57

Implementing SimpleSolitaire

package edu.uhcl.sce.simplesolitaire;

public class SimpleSolitaire{ private Deck deck; private Stack<Card>[] stacks;

SimpleSolitaire(){ deck = new Deck(); deck.shuffle(); stacks = new Stack[4]; for (int i=0; i<4; ++i){ stacks[i] = new Stack<Card>(); } dealFourCards(); }

public void dealFourCards(){ for (Stack<Card> s : stacks){ s.push(deck.deal()); } }

}

Now we need to write a method that deals the four cards and pushes each one onto a stack

dealFourCards() calls the deck object’s deal() method four times – once for each stack – and pushes the card object that is returned

Basic Java Programming (Flanagan; Drake)

ALGORITHM play() shuffle the deck deal four cards while not done print the four cards if there are cards left, we're not done else we're done, so stop get the next move from the user if the move is "pair" removePair() else if the move is "suit" removeLowCard() else if the move is "deal" dealFourCards() else stop

58

Implementing SimpleSolitaire

package edu.uhcl.sce.simplesolitaire;

public class SimpleSolitaire{ private Deck deck; private Stack<Card>[] stacks;

SimpleSolitaire(){ deck = new Deck(); deck.shuffle(); stacks = new Stack[4]; for (int i=0; i<4; ++i){ stacks[i] = new Stack<Card>(); } dealFourCards(); }

public void dealFourCards(){ for (Stack<Card> s : stacks){ s.push(deck.deal()); } }

}

Now we need to write a method that deals the four cards and pushes each one onto a stack

dealFourCards() calls the deck object’s deal() method four times – once for each stack – and pushes the card object that is returned

Basic Java Programming (Flanagan; Drake)

ALGORITHM play() shuffle the deck deal four cards while not done print the four cards if there are cards left, we're not done else we're done, so stop get the next move from the user if the move is "pair" removePair() else if the move is "suit" removeLowCard() else if the move is "deal" dealFourCards() else stop

A special kind of for loop called a “for-each” loop that can be used with arrays and Collections classes

59

For-Each Loop

ArrayList<Integer> myList = new ArrayList<Integer>();myList.add(new Integer(1));myList.add(new Integer(2));myList.add(new Integer(3));int sum = 0;for( Integer i : myList ) { sum += i;}

The for-each loop is a shorthand way of writing a loop that iterates through all the elements stored in a data structure

However, this works only with data structures that implement the java.lang.Iterable interface

Basic Java Programming (Goodrich, 244)

60

Implementing SimpleSolitaire

public static final Scanner IN = new Scanner(System.in);

public void play() { while (true){ System.out.println("\n" + this); boolean done = true; for (Stack<Card> s : stacks){ if (!(s.isEmpty())){ done = false; break; } } if (done){ System.out.println("You win!"); return; } System.out.println("pair,suit,deal,or quit?"); String command = IN.nextLine(); if (command.equals("pair")) { removePair(); } else if (command.equals("suit")) { removeLowCard(); } else if (command.equals("deal")) { dealFourCards(); } else return;}

Here’s the game loop in the play() method.

Basic Java Programming (Flanagan; Drake)

ALGORITHM play() shuffle the deck deal four cards while not done print the four cards if there are cards left, we're not done else we're done, so stop get the next move from the user if the move is "pair" removePair() else if the move is "suit" removeLowCard() else if the move is "deal" dealFourCards() else stop

We added a Scanner object to help with input

The cards are printed when the toString() method is called here

If any of the stacks are not empty, then we still have cards left and we are not finished

Bonus Lab

Reading a data file andadding an object to an array

62

References

Davison, Andrew, Killer Game Programming in Java. Sebastopol, CA:O'Reilly Media, Inc., 2005.

Deitel, H. M. and P. J. Deitel, Java How to Program. Upper Saddle River, NJ: Prentice Hall.

Goodrich, M. T. and R. Tamassia, Data Structures and Algorithms in Java. Hoboken, NJ: John Wiley & Sons, Inc., 2006.

Flanagan, D., Java in a Nutshell, 5th Edition. Sebastopol, CA:O'Reilly Media, Inc., 2005.

LaMothe, Andre, Tricks of the Windows Game Programming Gurus. Indianapolis: Sams Publishing, 2002.

Morrison, Michael, Beginning Game Programming. Indianapolis: Sams Publishing, 2005.

Naftalin, Maurice, and Philip Wadler, Java Generics and Collections. Sebastopol, CA:O'Reilly Media, Inc., 2007.


Recommended