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.

Slides:



Advertisements
Similar presentations
1 Todays Objectives Announcements Homework #1 is due next week Return Quiz 1 – answers are posted on the Yahoo discussion page site Basic Java Programming.
Advertisements

Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Computer Programming w/ Eng. Applications
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 The Stack ADT (§4.2) The Stack ADT stores arbitrary objects Insertions and deletions.
Java Software Solutions
 2005 Pearson Education, Inc. All rights reserved Introduction.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Applications of Stacks (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5)
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
AP Computer Science.  Not necessary but good programming practice in Java  When you override a super class method notation.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Building Java Programs
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Agenda Review User input Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays 2.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Topic 3 The Stack ADT.
1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.
Chapter 3 Introduction to Collections – Stacks Modified
1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Stack. Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
1 Today’s Objectives  Announcements The ethics paper is due next week, at the beginning of class Quiz 1 will be next week, at the beginning of class –Closed.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks  Introduction  Applications  Implementations  Complex Applications.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Copyright Curt Hill Variables What are they? Why do we need them?
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
ArrayLists (and the for-each loop) ArrayList example = new ArrayList (); example.add(4);
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
Week 10 - Wednesday.  What did we talk about last time?  Method example  Roulette simulation  Types in Java.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Click to edit Master text styles Stacks Data Structure.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Yanal Alahmad Java Workshop Yanal Alahmad
Stacks.
Multiple variables can be created in one declaration
Chapter 3 Assignment Statement
Stacks.
elementary programming
Introduction to Data Structure
Chapter 2 Programming Basics.
Just Enough Java 17-May-19.
Presentation 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 or  Quiz 1  Basic Java Programming Java 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 minutes Please 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 value Example: 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 operator int m, n = 11; m = n / 5; System.out.println("m = " + m); //What prints?  Modulo operator int 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 array int[] myArray; //variable declared, not initialized myArray = 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 index int[] 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 elements for( 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 bounds int[] 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 either primitive values or objects  Storing primitive variables in an array int[] myArray = new int[5]; myArray[0] = 42; System.out.println(myArray[0]);//what prints?  Storing reference variables in an array Card[] 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 either primitive values or objects  Storing primitive variables in an array int[] myArray = new int[5]; myArray[0] = 42; System.out.println(myArray[0]);//what prints?  Storing reference variables in an array Card[] 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 either primitive values or objects  Storing primitive variables in an array int[] myArray = new int[5]; myArray[0] = 42; System.out.println(myArray[0]);//what prints?  Storing reference variables in an array Card[] 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. Ks9h3dAc cards.size == 4 cards 01234

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 library import java.util.ArrayList;  You need to know how to instantiate an ArrayList object private ArrayList cards; cards = new ArrayList ();  You need to know some of the operations intsize()‏ booleanisEmpty()‏ Eadd(E element)‏ Eget(int index) Eset(int index, E element)‏ Eremove(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 variable Use access specifier only when this is an instance variable

21 Implementing Deck package edu.uhcl.sce.simplesolitaire; import java.util.ArrayList; public class Deck{ private ArrayList cards; public Deck(){ cards = new ArrayList (); 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 Deck Basic 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 cards; public Deck(){ cards = new ArrayList (); 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 Deck Basic 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 cards; public Deck(){ cards = new ArrayList (); 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” class Primitive data typeWrapper class booleanBoolean charCharacter byteByte intInteger longLong shortShort floatFloat doubleDouble 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 object 2. 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 charList = new ArrayList (); Character first = new Character('a'); charList.add(first); } Basic Java Programming (Goodrich, 222–230)‏ Instantiate an object Add it to the ArrayList

29 Storing Data in an ArrayList 1. Create the ArrayList object 2. 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 charList = new ArrayList (); 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 object 2. 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 charList = new ArrayList (); 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 methods Wrapper classSome examples of its static methods Characterpublic 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"); Integerpublic 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 cards; public Deck(){ cards = new ArrayList (); 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 cards 1.If two cards have the same rank, discard both 2.If two cards have the same suit, discard the lower rank card 3.Deal four more cards Requirements Start 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 cards 1.If two cards have the same rank, discard both 2.If two cards have the same suit, discard the lower rank card 3.Deal four more cards Requirements Start 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 cards 1.If two cards have the same rank, discard both 2.If two cards have the same suit, discard the lower rank card 3.Deal four more cards Requirements Start 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 cards 1.If two cards have the same rank, discard both 2.If two cards have the same suit, discard the lower rank card 3.Deal four more cards Requirements Start 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 cards 1.If two cards have the same rank, discard both 2.If two cards have the same suit, discard the lower rank card 3.Deal four more cards Requirements Start 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 cards Basic 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. Rank In 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 library import java.util.Stack;  You need to know how to instantiate a Stack object private Stack st; st = new Stack ();  You need to know the operations Epush( E element )‏ Epop() Epeek()‏ booleanempty()‏  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 [] stacks; SimpleSolitaire(){ deck = new Deck(); deck.shuffle(); stacks = new Stack[4]; for (int i=0; i<4; ++i){ stacks[i] = new Stack (); } 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 algorithm and a program ALGORITHM reverseString(s)‏ Input: a string Output: the string reversed Stack st StringBuilder sb Basic Java Programming (Goodrich, 159)‏ ADT for java.util.Stack Epush( E element )‏ Epop() Epeek()‏ booleanempty()‏ Tips for writing an algorithm Use the correct data structure Use the correct ADT operations Use object-oriented syntax Indent clearly Use a return statement at the end Tips for writing an algorithm Use the correct data structure Use the correct ADT operations Use object-oriented syntax Indent clearly Use a return statement at the end

53 Using a stack in an algorithm and a program ALGORITHM reverseString(s)‏ Input: a string Output: the string reversed Stack st StringBuilder sb for 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 structure Use the correct ADT operations Use object-oriented syntax Indent clearly Use a return statement at the end Tips for writing an algorithm Use the correct data structure Use the correct ADT operations Use object-oriented syntax Indent clearly Use a return statement at the end

54 Using a stack in an algorithm and a program ALGORITHM reverseString(s)‏ Input: a string Output: the string reversed Stack st StringBuilder sb for 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 structure Use the correct ADT operations Use object-oriented syntax Indent clearly Use a return statement at the end Tips for writing an algorithm Use the correct data structure Use the correct ADT operations Use object-oriented syntax Indent clearly Use a return statement at the end

55 Using a stack in an algorithm and a program ALGORITHM reverseString(s)‏ Input: a string Output: the string reversed Stack st StringBuilder sb for 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 structure Use the correct ADT operations Use object-oriented syntax Indent clearly Use a return statement at the end Tips for writing an algorithm Use the correct data structure Use the correct ADT operations Use object-oriented syntax Indent clearly Use a return statement at the end

56 Using a stack in an algorithm and 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 st StringBuilder sb for 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()‏ ALGORITHM reverseString(s)‏ Input: a string Output: the string reversed Stack st StringBuilder sb for 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 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 [] stacks; SimpleSolitaire(){ deck = new Deck(); deck.shuffle(); stacks = new Stack[4]; for (int i=0; i<4; ++i){ stacks[i] = new Stack (); } dealFourCards(); } public void dealFourCards(){ for (Stack 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 [] stacks; SimpleSolitaire(){ deck = new Deck(); deck.shuffle(); stacks = new Stack[4]; for (int i=0; i<4; ++i){ stacks[i] = new Stack (); } dealFourCards(); } public void dealFourCards(){ for (Stack 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 myList = new ArrayList (); 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 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 and adding an object to an array

62 References Davison, Andrew, Killer Game Programming in Java. Sebastopol, CA:O'Reilly Media, Inc., 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., Flanagan, D., Java in a Nutshell, 5th Edition. Sebastopol, CA:O'Reilly Media, Inc., LaMothe, Andre, Tricks of the Windows Game Programming Gurus. Indianapolis: Sams Publishing, Morrison, Michael, Beginning Game Programming. Indianapolis: Sams Publishing, Naftalin, Maurice, and Philip Wadler, Java Generics and Collections. Sebastopol, CA:O'Reilly Media, Inc., 2007.