Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2004 Pearson Addison-Wesley. All rights reserved6-1 Program Development In your CS102 project, and in many others, the basic activities are:  requirements.

Similar presentations


Presentation on theme: "© 2004 Pearson Addison-Wesley. All rights reserved6-1 Program Development In your CS102 project, and in many others, the basic activities are:  requirements."— Presentation transcript:

1 © 2004 Pearson Addison-Wesley. All rights reserved6-1 Program Development In your CS102 project, and in many others, the basic activities are:  requirements – WHAT to do  design (UI and detailed design) – HOW to do  implementation – DO it  testing – CHECK errors and DEBUG They overlap and interact Requirements and Design stages are extremely important

2 © 2004 Pearson Addison-Wesley. All rights reserved6-2 Requirements Tasks that a program must accomplish What to do, not how to do it Possibly Problem description Functionalities and feature lists Use-case descriptions

3 © 2004 Pearson Addison-Wesley. All rights reserved6-3 Design How a program will accomplish its requirements  Break the solution into manageable pieces  What each piece will do  Which classes and objects are needed, and how they will interact  Detailed design include how individual methods will accomplish their tasks UI Design  How will it look like? How the system will interact with the user?  Storyboard, illustration, description of the interactions

4 © 2004 Pearson Addison-Wesley. All rights reserved6-4 Implementation, Testing, Debugging, Maintenance Implementation: translating a design into source code Testing attempts to find errors  Ensure to solve the intended problem under all the constraints specified in the requirements Debugging: determining the cause of a problem and fixing it Maintenance

5 6-5 HangMan: Partial Requirements In the game of Hangman the player must find a word chosen secretly by the program. The player can try one letter at a time and the program says how many times and where the letter appears in the secret word. If the player tries more than a certain number of incorrect letters (i.e. letters which do not appear in the secret word), they lose the game and the program tells them the secret word, otherwise they continue until they uncover the complete word. * by David Davenport

6 6-6 HangMan: Partial Requirements Usually, players are able to see the partially formed word made by the letters so far correctly guessed, any unknown letters being left blank. They may also be able to see the set of all letters that might be in the word (with those already used possibly being removed), as well as the number of incorrect tries made so far (this is often shown graphically, by the number of visible body parts of a cartoon character which is hung when complete -hence the name of the game!)

7 6-7 HangMan: Partial Design class Hangman constructors  + Hangman() // default max 6 incorrect tries, English alphabet, // chooses secretWord from fixed list. set  all letters to English alphabet  max allowed incorrect tries to 6, no of incorrect tries to 0,  used letters to empty set,  secret word by calling choose-secret-word method  knowsofar to StringBuffer of same length as secret word, but all characters are stars ('*').

8 6-8 HangMan: Partial Design properties  secretWord : StringBuffer  allLetters : StringBuffer  usedletters : StringBuffer  numberOfIncorrectTries : int  maxAllowedIncorrectTries : int  knownSoFar : StringBuffer // secretWord but with chars not yet found blanked out

9 6-9 HangMan: Partial Design methods  + getAllLetters() : String  + getUsedLetters() : String  + getNumOfIncorrectTries() : int  + getMaxAllowedIncorrectTries : int  + getKnownSoFar() : String // returns partial word formed with known letters only  + tryThis( letter) : int // returns number of occurrences of letter in secretWord  + isGameOver() : boolean  + hasLost() : boolean  - chooseSecretWord() // initially use fixed list, called from constructor

10 6-10 HangMan: Notes on a Method tryThis(letter): Returns number of times the letter occurs in the secret word. Adds letter to used letters. Updates known so far to show the letter at each position it exists in secret word. If the letter is not in secret word then increment number of incorrect tries. Method should return error values to indicate if the letter is not valid (-1), if the letter was already used (-2), and indicate if game over (-3).

11 6-11 HangMan Game: Main method Need a main method to start the game by  Creating instance of Hangman class  Calling its methods Allow the user to interact with it  UI -- could be as simple as the text mode using the keyboard only, or more sophisticated graphics The program must repeatedly get letters from the user and try them  A while loop until the game is complete

12 6/11/2016 CS101 - Algorithms & Programming I 12 Java OOP Software Software System  Set of objects  Which interact with each other One object will send a message to another object asking it to do a particular task. The first object does not need to know how the task is done (only how to request that it be done.) This corresponds to calling one of the second object’s methods! Created (instantiated) from class definitions Person AyseDavid “David” David: Say your name

13 6/11/2016 CS101 - Algorithms & Programming I 13 Coding Java Classes // header public class Person { // properties // constructors // methods } public void sayName() { System.out.println( name); } Stringname; intage; doublesalary; Stringcomments; public Person( StringtheName, inttheAge ) { name = theName; age = theAge; comments = “”; }

14 6/11/2016 CS101 - Algorithms & Programming I 14 Coding Java Classes public double getNetSalary() { double netSalary; netSalary = salary - TAX; return netSalary; } public String getName() { return name; } public String getComments() { return comments; } public void setComments( String someText) { comments = someText; } “get” & “set” methods for some properties (no setName!) Variables which are not parameters or properties must be defined locally. public void increaseAge() { age = age + 1; }

15 6/11/2016 CS101 - Algorithms & Programming I 15 Creating & Using Objects Always  Declare variable to “hold” object  Create object using “new” statement  Call object’s methods “Ayse” name: 18 age: 0.0 salary: “” comments: aStudent {Person} Person aStudent; aStudent = new Person( “Ayse”, 18); aStudent.sayName(); Put this in method of another class, (e.g main method)

16 6/11/2016 CS101 - Algorithms & Programming I 16 Creating & Using Objects Person aStudent; aStudent = new Person( “Ayse”, 18); Person friend; friend = new Person( “David”, 22); “Ayse” name: 18 age: 0.0 salary: “” comments: aStudent {Person} “David” name: 22 age: 0.0 salary: “” comments: friend {Person} friend.increaseAge(); aStudent.setComments( “Good student”); 23 “Good student”

17 © 2004 Pearson Addison-Wesley. All rights reserved6-17 Identifying Classes and Objects The core activity: Determine the classes and objects Reuse the classes (a class library, etc.) One way to identify potential classes is to identify the objects discussed in the requirements Objects are generally nouns, and the services that an object provides are generally verbs

18 © 2004 Pearson Addison-Wesley. All rights reserved6-18 Identifying Classes and Objects A partial requirements document: The user must be allowed to specify each product by its primary characteristics, including its name and product number. If the bar code does not match the product, then an error should be generated to the message window and entered into the error log. The summary report of all transactions must be structured as specified in section 7.A. Of course, not all nouns will correspond to a class or object in the final solution

19 © 2004 Pearson Addison-Wesley. All rights reserved6-19 Identifying Classes and Objects Remember: A class is a concept for a group (classification) of objects with the same behaviors  Singular nouns: Coin, Student, Employee Need to decide whether something should be represented as a class  Should Address of an employee be an instance variable or an object itself? When a class becomes too complex, it often should be decomposed into multiple smaller classes to distribute the responsibilities

20 © 2004 Pearson Addison-Wesley. All rights reserved6-20 Identifying Classes and Objects Define the classes with the proper amount of detail May be unnecessary to create separate classes for each type of appliance in a house  Sufficient to define a more general Appliance class with appropriate instance data It all depends on the details of the problem being solved

21 Example: A Card Game* Design & implement a program to play a simple game of cards between four players. To begin, a full pack of cards are shuffled and dealt face- down to the players. The game then proceeds in rounds. For each round, players play the top card from their hand and add it face-up to a pile on the table in front of them. The player who plays the highest value card is the winner of the round and their score is incremented by one. When all of the cards have been played the player with the highest score is declared the winner of the game. * by David Davenport

22 Design & implement a program to play a simple game of cards between four players. To begin, a full pack of cards are shuffled and dealt face- down to the players. The game then proceeds in rounds. For each round, players play the top card from their hand and add it face-up to a pile on the table in front of them. The player who plays the highest value card is the winner of the round and their score is incremented by one. When all of the cards have been played the player with the highest score is declared the winner of the game. Example: A Card Game

23 Picture it… Objects the Game? Pack of cards Players 1, 2, 3 & 4 the Table? Score card? (Player 1, 2, 3 & 4 scores) Players 1, 2, 3 & 4 Cards on table Players 1, 2, 3 & 4 Cards in hand player score Table player Pack of cards

24 Classes CleverGame Pack of cards 4 Players Scorecard (with 4 scores on) 4 Piles of cards on table ScoreCard Set of scores Player Name Set of cards in hand Cards Collection of cards Card Face value Suit

25 Design & implement a program to play a simple game of cards between four players. To begin, a full pack of cards are shuffled and dealt face- down to the players. The game then proceeds in rounds. For each round, players play the top card from their hand and add it face-up to a pile on the table in front of them. The player who plays the highest value card is the winner of the round and their score is incremented by one. When all of the cards have been played the player with the highest score is declared the winner of the game. Example: A Card Game*

26 Simple Game class properties Pack of cards 4 Players 4 Scores 4 Piles of cards on table constructor ( 4 players) creates the game with the given players methods playGame() plays a complete game sets scores getScore( player number) returns players score Represents a single card game played by 4 players

27 CleverGame class properties Pack of cards, 4 Players ScoreCard, 4 Piles of cards on table constructor ( 4 players) creates the game with the given players Methods + playTurn(Player, Card) : boolean + isTurnOf(Player) : boolean + isGameOver() : boolean + getScore( playerNumber) : int + getName( playerNumber) : String + getRoundNo() : int + getTurnOfPlayerNo() : int + getWinners() : set of Player Represents a single card game played by 4 players

28 Player class properties name set of cards in hand constructor ( name) creates player with name & empty hand methods getName() returns players name add( Card) add the card to players hand playCard() removes and returns the top card from the players hand Represents a single player for a card game

29 ScoreCard class properties Set of scores constructor ( noOfScores) initialises scorecard with noOfScores entries all set to zero methods + getScore(scoreNo) : int returns specified score + update( scoreNo, amount) add amount to scoreNo Represents a ScoreCard for a card game

30 Cards class properties Collection of cards constructor () creates a collection of cards with no cards in it! methods getTopCard() removes & returns top card from collection addTopCard( Card) adds the card to the collection createFullPackOfCards() shuffle() randomises order of cards in collection Represents a set of zero or more playing cards

31 Card class properties faceValue suit constructor ( faceValue, suit) creates card with given face value & suit constructor ( cardNumber) creates card with given position number in ordered pack! methods getFaceValue() returns faceValue getSuit() returns suit toString() Represents a single playing card

32 Playing the Game Algorithm for playGame method Create the pack of cards Shuffle the pack Deal all the pack between the players Create empty piles of cards on table Set all players scores to zero For each round (until players have no cards left) Each player plays card by adding it to their pile on table Find biggest value card on top of piles on table Increment scores of players who played cards with biggest value

33 Playing the Game public void initGame() // create new pack & shuffle // create empty set of cards on table for each player // deal all cards to players // create score card // create piles of cards on table // set round no to 0 // setturn of player no to 0

34 Playing the Game public boolean playTurn( SimplePlayer p, Card c) // if game is over return false // if it's not p's turn return false // p's turn so take p's card & put on table // if not end of round then // move to next players turn else // end of round, update scores & // if not end of game then // move to next round & next player's turn return true private void updateScores() // find max of cards just placed on table // increment scores of player(s) with max card(s)

35 © 2004 Pearson Addison-Wesley. All rights reserved6-35 Static Methods class Helper { public static int cube (int num) { return num * num * num; } Because it is declared as static, the method can be invoked as value = Helper.cube(5);

36 © 2004 Pearson Addison-Wesley. All rights reserved6-36 Static Class Members Static Variables: only one copy of the variable exists (not # of objs) All objects share its static variables Changing the value changes it for all Static methods cannot reference instance variables  Instance variables don't exist until an object exists Static methods can reference static variables or local variables

37 © 2004 Pearson Addison-Wesley. All rights reserved6-37 Static Class Members Static methods and static variables often work together The following example keeps track of how many Slogan objects have been created using a static variable, and makes that information available using a static method See SloganCounter.java (page 294)SloganCounter.java See Slogan.java (page 295)Slogan.java

38 © 2004 Pearson Addison-Wesley. All rights reserved6-38 Class Relationships 1- Dependency: A uses B - A invokes the methods of B  No dependency -> too complex classes  Too much dependency -> Too complex design 2- Aggregation: A has-a B  A references B as instance data 3- Inheritance: A is-a B

39 © 2004 Pearson Addison-Wesley. All rights reserved6-39 Dependency Some dependencies occur between objects of the same class A method of the class may accept an object of the same class as a parameter For example, the concat method of the String class takes as a parameter another String object str3 = str1.concat(str2); This drives home the idea that the service is being requested from a particular object

40 © 2004 Pearson Addison-Wesley. All rights reserved6-40 Dependency The following example defines a class called Rational to represent a rational number A rational number is a value that can be represented as the ratio of two integers Some methods of the Rational class accept another Rational object as a parameter See RationalTester.java (page 297)RationalTester.java See RationalNumber.java (page 299)RationalNumber.java

41 © 2004 Pearson Addison-Wesley. All rights reserved6-41 Aggregation In the following example, a Student object is composed, in part, of Address objects A student has an address (in fact each student has two addresses) See StudentBody.java (page 304)StudentBody.java See Student.java (page 306)Student.java See Address.java (page 307)Address.java An aggregation association is shown in a UML class diagram using an open diamond at the aggregate end

42 © 2004 Pearson Addison-Wesley. All rights reserved6-42 Object Reference this this in an instance method refers to the corresponding object When method tryMe is called: obj1.tryMe(); obj2.tryMe(); In the first invocation, the this reference refers to obj1; in the second it refers to obj2 Two common usage: 1- to pass the corresponding object as a parameter 2- to access fields shadowed by local variables.

43 6/11/2016 CS101 - Algorithms & Programming I 43 1- Passing this as a Parameter public class MyInt { private int ival; public MyInt(int val) { ival=val; } public boolean isGreaterThan(MyInt o2) { return (ival > o2.ival); } public boolean isLessThan(MyInt o2) { return (o2.isGreaterThan(this)); } } in some other place MyInt x1=new MyInt(5), x2=new MyInt(6); x1.isGreaterThan(x2); x1.isLessThan(x2);

44 © 2004 Pearson Addison-Wesley. All rights reserved6-44 2- Access fields shadowed by local variables Distinguish the instance variables from method parameters with the same names public Account (String name, long acctNumber, double balance) { this.name = name; this.acctNumber = acctNumber; this.balance = balance; }

45 6/11/2016 CS101 - Algorithms & Programming I 45 Methods A method can be:  an instance method (declared without using keyword static ), or  a class method (declared using keyword static, it is also known as a static method). An instance method is associated with an object.  If it accesses an instance variable, it accesses of the copy of that instance variable in the current object. A static method is a class-method and there is only one copy for it.  All instances of that class share that single copy.  A static method cannot access an instance variable or an instance method.

46 6/11/2016 CS101 - Algorithms & Programming I 46 Overloaded Methods static void m(int x, int y) { System.out.println("m-i-i"); } static void m() { System.out.println("m-noarg"); } static void m(double x, double y) { System.out.println("m-d- d"); } static void m(int x, double y) { System.out.println("m-i- d"); } static void m(double x, int y) { System.out.println("m-d- i"); } static void m(int x) { System.out.println("m-i"); } to invoke this method m(1,2); m(); m(1.1,2.2); m(1,2.2); m(1.1,2); m(1);

47 © 2004 Pearson Addison-Wesley. All rights reserved6-47 Method Design High-level design:  identifying primary classes and objects  assigning primary responsibilities Low-level: the design of key methods  Make the methods relatively short A public service method may call private support methods

48 6/11/2016 CS101 - Algorithms & Programming I 48 Recap – Modifiers publicprivateprotected package The class itself yes Classes in the same package yesnoyes Sub-classes in a different package yesnoyesno Non- subclasses in a different package yesno

49 6/11/2016 CS101 - Algorithms & Programming I 49 Recap - Variables 1.instance variables -- declared in the class (without using static keyword) 2.class variables (static variables) - declared in the class (with using static keyword) 3.local variables – declared in a method or as its formal parameters. An instance method of a class can refer (just using their names) to all instance variables, all static variables declared in the class, and all its local variables. A static method of a class cannot refer to any instance variable declared in that class. It can only refer to static variables and its local variables.

50 6/11/2016 CS101 - Algorithms & Programming I 50 Variables (cont.) class C { int x; static int y; public void printX() { System.out.println(“x: “+x); } public static void printY() { System.out.println(“y: “+y); } public void m1(int a, int b) { int c=a+b; x=a; y=b; printX(); printY(); } public static m2(int a, int b) { x=a;  ILLEGAL y=b; printX();  ILLEGAL printY(); } }

51 6/11/2016 CS101 - Algorithms & Programming I 51 Recall - Dot Operator (cont.) class C1 { public int x; public static int y=5; public C1() { x=1; } public void setX(int val) { x=val; } public static void printY() { System.out.println(“y: “ + y); } } // in a method of some other class C1 o1,o2;o1.x = 2; C1.y = 10;o2.x = 3; C1.x = 10;  ILLEGALo1.y = 4; C1.printY();o2.y = 5; C1.setX(10);  ILLEGALC1.y = 6; o1 = new C1(); o1.setX(7); o2 = new C1();o2.setX(8); o1.printY(); o2.printY();


Download ppt "© 2004 Pearson Addison-Wesley. All rights reserved6-1 Program Development In your CS102 project, and in many others, the basic activities are:  requirements."

Similar presentations


Ads by Google