Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 14 Introduction to Programming Mr. Joshua Stough March 23, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.

Similar presentations


Presentation on theme: "COMP 14 Introduction to Programming Mr. Joshua Stough March 23, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218."— Presentation transcript:

1 COMP 14 Introduction to Programming Mr. Joshua Stough March 23, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218

2 Today Short Review Program 4 –Static –Arrays –Reserved word this

3 Announcements

4 Review Scope public class Rectangle { // variables declared here are class-level // available in all methods in Rectangle class public int computeArea() { // variables declared here are method-level // only available in computeArea() } public void print() { // variables declared here are method-level // only available in print() }

5 Review Overloading Methods Overloading - the process of using the same method name for multiple methods The signature of each overloaded method must be unique –number of parameters –type of the parameters –not the return type of the method, though The compiler determines which version of the method is being invoked by analyzing the parameters

6 Review public Rectangle (int l, int w) { length = l; width = w; } public class Rectangle { private int length; private int width; Rectangle r2 = new Rectangle (5, 10); public Rectangle () { length = 0; width = 0; }

7 Review A method should be relatively small –it should be able to be understood as a single entity –its name should fully describe its function A potentially large method should be decomposed into several smaller methods as needed for clarity A service method of an object may call one or more support methods to accomplish its goal

8 Thought Exercise Write a method for the Rectangle class called printBox that will print the rectangle as a box made of % example: length = 3, width = 5 %%% % %%%

9 public void printBox () { for (int i = 1; i <= width; i++) System.out.print("%"); System.out.println( ); for (int i = 1; i <= length - 2; i++) { System.out.print("%"); for (int j = 1; j <= width - 2; j++) System.out.print(" "); System.out.println("%"); } for (int i = 1; i <= width; i++) System.out.print("%"); System.out.println( ); } %%%% % % %%%% length = 3, width = 8

10 Blackjack Playing cards –13 faces (2-10, Jack, Queen, King, Ace) –4 suits (Spades, Clubs, Diamonds, Hearts) Deck of cards –52 cards (13 * 4) Blackjack Points –Jack, Queen, King: 10 –Ace: 1 or 11

11 Blackjack Goal: Have the hand (group of cards) with the total point value closest to 21 ("Blackjack") without going over Play –get two cards –"hit" (add a card) or "stand" Demo (program 6) www.cs.unc.edu/~mcweigle/courses/comp14-spr04/code/prog/Blackjack.html

12 Program 4 Due: Wednesday, March 30 at 11:59pm 75 points Implement Card class Implement method for determining point value given a Card object Create 4 Card objects, print each card and its point value, sum the total point value of the 4 cards, adjust total if it's over 21 and there are Aces You will be graded on how your program works with other cards, too

13 Card class What should be the member variables of a playing card? –what things completely describe an individual card? –what data types should we use? Don't forget the visibility modifiers face suit if we use constants to represent the words, we can store the face and suit with integers

14 Program 4 Outlines Card.java BlackjackGame.java Blackjack.java

15 The toString Method Special method in Java classes Produces a String object based on the current object, suitable for printing Mapped to the '+' operator Also called when the object is a parameter in a print() or println() method There is a default toString method, but it's better if we write our own

16 Rectangle.java public String toString() { String result = ""; result += "length: " + length + "\n"; result += "width: " + width; return (result); } Rectangle r = new Rectangle (2,3); System.out.println (r); length: 2 width: 3

17 toString and Program 4 Should be included as part of the Card class Return a String that contains the face and suit of the card Examples: –Ace of Spades –4 of Diamonds –Queen of Hearts

18 The Modifier static In the method heading, specifies that the method can be invoked by using the name of the class –no object has to be created in order to use the method –can't call a non-static method from a static method –can't access non-static variables from a static method If used to declare data member, data member invoked by using the class name –no object has to be created in order to use the variables

19 static and Program 4 public class Card { public static final int ACE = 14; public class BlackjackGame { public static int calcPoints (Card card) Card.ACE BlackjackGame.calcPoints

20 static Variables Shared among all objects of the class Memory created for static variables when class is loaded –memory created for instance variables (non-static) when an object is instantiated (using new) If one object changes the value of the static variable, it is changed for all objects of that class

21 Illustrate Class (pg. 421) public class Illustrate { private int x; public static int y; private static int count; public Illustrate() { x = 0; } public Illustrate (int a) { x = a; } public static void incrementCount() { count++; } Illustrate obj1 = new Illustrate(3); x 3 x 5 0 y count 0 obj1 obj2 Illustrate.incrementCount(); 1 1 Illustrate obj2 = new Illustrate(5); Illustrate.y++;

22 Thinking about Blackjack We know how to represent one card How do we represent a deck of 52 cards? 52 separate variables? Card aceOfSpades; Card 2OfSpades; Card 3OfSpades;... Card[] deck;

23 Arrays An array is a list of values that can be represented by one variable Members of an array must all have the same data type Each value is stored at a specific, numbered position in the array –the number corresponding to each position is called an index or subscript All arrays have a length –number of elements the array can hold 01 23

24 Declaring Arrays type[] name; The array (element) data type Empty square brackets The array (variable) name Creates a reference variable called name that can point to an array of type elements. 01 23

25 Declaring Arrays Examples // array of characters char[] characterSet; // array of counters (integers) int[] counter; // array of grades (doubles) double[] grade; counter characterSet grade 01 23

26 Instantiating Arrays You must instantiate (create) arrays –the size of an array is typically not known before run time name = new type[size]; The array (element) data type The new operator The array (variable) name The assignment operator The number of elements 01 23

27 Instantiating Arrays Examples // instantiate an array of counters counter = new int[5]; // instantiate the array of grades numStudents = 10; grade = new double[numStudents]; counter 0 1 2 3 4 0 <= index < size 01 23

28 Declaration and Instantiation type[] name = new type[size]; DeclarationInstantiation 01 23

29 Arrays of Objects Can use arrays to manipulate objects Create array of objects Must instantiate each object in array classname[] array = new classname[size]; for(int j=0; j <array.length; j++) { array[j] = new classname(); }

30 Example int[] num = new int[5]; 01 23

31 Array Access Examples averageScore = (score[0]+score[1]+score[2])/3; numStudents = 3; totalScore = 0; for (int i = 0; i < numStudents; i++) { totalScore += score[i]; } averageScore = totalScore/numStudents; double score[] = new score[3]; score[0] = 98.3; score[1] = 57.8; score[2] = 93.4; often use loops for access 01 23

32 Array Length Arrays have length –an internal variable called length –number of elements in array –access the length variable using the “dot’ notation (arrayname. length) // loop through the array of test scores sumOfScores = 0; for (int i=0; i<scores.length; i++) { sumOfScores += scores[i]; } 01 23

33 int counter[] = {0, 0, 0, 0, 0}; char[] characterSet = {‘a’,’b’,’c’}; // etc. Initializing Arrays Array elements are variables too! –if you don’t initialize, the contents are undefined When and how? –if you don’t yet know the size initialize at run time, typically with a loop –if you know how many elements perhaps use an initializer list 01 23

34 Lists the initial value for the elements of an array Items are separated by commas and the list is in braces {} The size of the array is determined by the number of items in the list int[] scores = {87, 98, 45}; Can only be used in the same statement as declaring the array NOTint[] scores; scores = {87, 98, 45}; Initializer Lists 01 23

35 The Reference this Reserved word Refers to instance variables and methods of a class Allows you to distinguish between member variables and local variables with the same name

36 Rectangle.java public class Rectangle { private int length; private int width; public Rectangle (int length, int width) { this.length = length; this.width = width; }

37 this and Program 4 public class Card { public Card (int face, int suit) { } If member variables were named face and suit, how can we assign the member variable face the value of the formal parameter face?

38 Reference Variables as Parameters If a formal parameter is a reference variable: –copies value of corresponding actual parameter –value of actual parameter is address of object where actual data is stored –both formal and actual parameter refer to same object

39 Passing Reference Variables And Program 4 public class BlackjackGame { public static int calcPoints(Card card) { } Card card1 = new Card (2, Card.HEARTS); card1 face 2 suit 0 card int points = BlackjackGame.calcPoints(card1); 2 points

40 Next Time in COMP 14 Arrays Reading Assignment: Ch 9 (pgs. 467- 491)


Download ppt "COMP 14 Introduction to Programming Mr. Joshua Stough March 23, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218."

Similar presentations


Ads by Google