1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.

Slides:



Advertisements
Similar presentations
Computers and Scientific Thinking David Reed, Creighton University Conditional Execution 1.
Advertisements

Basic Java Constructs and Data Types – Nuts and Bolts
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Introduction to C Programming
Methods Java 5.1 A quick overview of methods
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
VBA Modules, Functions, Variables, and Constants
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Program Design and Development
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Python quick start guide
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
1 CSC 222: Object-Oriented Programming Spring 2013 interacting objects  abstraction, modularization  internal vs. external method calls  expressions,
Fruitful functions. Return values The built-in functions we have used, such as abs, pow, int, max, and range, have produced results. Calling each of these.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
4.1 Instance Variables, Constructors, and Methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
1 MT258 Computer Programming and Problem Solving Unit 7.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
1 CSC 221: Computer Programming I Fall 2006 repetition & simulations  conditional repetition, while loops  examples: dot race, paper folding puzzle,
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 11 Conditional.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 CSC 221: Computer Programming I Spring 2008 Class design & strings  design principles  cohesion & coupling  class example: graphical DotRace  static.
1 CSC 221: Computer Programming I Fall 2005 interacting objects  abstraction, modularization  internal vs. external method calls  primitives vs. objects.
1 CSC 221: Computer Programming I Fall 2004 interacting objects  abstraction, modularization  internal method calls  object creation, external method.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Chapter 4 Introduction to Classes, Objects, Methods and strings
1 if / else statements. 2 Conditionals “If you eat your vegetables, then you can have dessert.” “If you do your homework, then you may go outside to play,
1 CSC 221: Computer Programming I Fall 2009 interaction & repetition  modular design: dot races  constants, static fields  conditional repetition, while.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
Chapter 3 Object Interaction.  To construct interesting applications it is not enough to build individual objects  Objects must be combined so they.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SEEM Java – Basic Introduction, Classes and Objects.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
Week 12 - Wednesday.  What did we talk about last time?  Hunters and prey.
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
Week 12 - Monday.  What did we talk about last time?  Defining classes  Class practice  Lab 11.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
1 CSC 221: Computer Programming I Fall 2005 repetition & simulations  conditional repetition, while loops  examples: dot race, paper folding puzzle,
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
1 CSC 221: Computer Programming I Fall 2005 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
1 CSC 221: Computer Programming I Fall 2005 graphics & design  Dot & DotRace revisited  Circle class implementation  adding Circle methods  static.
Building Java Programs
CSC 222: Object-Oriented Programming Fall 2015
Methods Chapter 6.
Group Status Project Status.
CMSC 202 Java Primer 2.
Chapter 4 Writing Classes.
CSC 222: Object-Oriented Programming Spring 2012
CSC 222: Object-Oriented Programming Spring 2012
Computers and Scientific Thinking David Reed, Creighton University
Presentation transcript:

1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators variable scope

2 Dot races consider the task of simulating a dot race (as on stadium scoreboards) different colored dots race to a finish line at every step, each dot moves a random distance (say between 1 and 5 units) the dot that reaches the finish line first wins! behaviors? create a race (dots start at the beginning) step each dot forward a random amount access the positions of each dot display the status of the race reset the race we could try modeling a race by implementing a class directly store positions of the dots in fields have each method access/update the dot positions BUT: lots of details to keep track of; not easy to generalize

3 A modular design instead, we can encapsulate all of the behavior of a dot in a class Dot class: create a Dot (with a given color) access the dot's position take a step reset the dot back to the beginning display the dot's color & position once the Dot class is defined, a DotRace will be much simpler DotRace class: create a DotRace (with two dots) access either dot's position move both dots a single step reset both dots back to the beginning display both dots' color & position

4 Dot class public class Dot { private Die die; private String dotColor; private int dotPosition; public Dot(String color) { this.die = new Die(5); this.dotColor = color; this.dotPosition= 0; } public int getPosition() { return this.dotPosition; } public void step() { this.dotPosition += this.die.roll(); } public void reset() { this.dotPosition = 0; } public void showPosition() { System.out.println(this.dotColor + ": " + this.dotPosition); } more naturally: fields store a Die (for generating random steps), color & position constructor creates the Die object and initializes the color and position fields methods access and update these fields to maintain the dot's state CREATE AND PLAY

5 Magic numbers the Dot class works OK, but what if we wanted to change the range of a dot? e.g., instead of a step of 1-5 units, have a step of 1-8 would have to go and change die = new Die(5); to die = new Die(8); having "magic numbers" like 5 in code is bad practice unclear what 5 refers to when reading the code requires searching for the number when a change is desired public class Dot { private Die die; private String dotColor; private int dotPosition; public Dot(String color) { this.die = new Die(5); this.dotColor = color; this.dotPosition= 0; } public int getPosition() { return this.dotPosition; } public void step() { this.dotPosition += this.die.roll(); } public void reset() { this.dotPosition = 0; } public void showPosition() { System.out.println(this.dotColor + ": " + this.dotPosition); }

6 Constants better solution: define a constant a constant is a variable whose value cannot change use a constant any time a "magic number" appears in code a constant declaration looks like any other field except the keyword final specifies that the variable, once assigned a value, is unchangeable the keyword static specifies that the variable is shared by all objects of that class since a final value cannot be changed, it is wasteful to have every object store a copy of it instead, can have one static variable that is shared by all by convention, constants are written in all upper-case with underscores public class Dot { private static final int MAX_STEP = 5; private Die die; private String dotColor; private int dotPosition; public Dot(String color) { this.die = new Die(Dot.MAX_STEP); this.dotColor = color; this.dotPosition= 0; } public int getPosition() { return this.dotPosition; } public void step() { this.dotPosition += this.die.roll(); } public void reset() { this.dotPosition = 0; } public void showPosition() { System.out.println(this.dotColor + ": " + this.dotPosition); }

7 Static fields in fact, it is sometimes useful to have static fields that aren't constants if all dots have the same range, there is no reason for every dot to have its own Die we could declare the Die field to be static, so that the one Die is shared by all dots note: methods can be declared static as well e.g., random is a static method of the predefined Math class you call a static method by specifying the class name as opposed to an object name: Math.random() MORE LATER public class Dot { private static final int MAX_STEP = 5; private static Die die = new Die(Dot.MAX_STEP); private String dotColor; private int dotPosition; public Dot(String color) { this.dotColor = color; this.dotPosition= 0; } public int getPosition() { return this.dotPosition; } public void step() { this.dotPosition += Dot.die.roll(); } public void reset() { this.dotPosition = 0; } public void showPosition() { System.out.println(this.dotColor + ": " + this.dotPosition); }

8 DotRace class public class DotRace { private Dot redDot; private Dot blueDot; public DotRace() { this.redDot = new Dot("red"); this.blueDot = new Dot("blue"); } public int getRedPosition() { return this.redDot.getPosition(); } public int getBluePosition() { return this.blueDot.getPosition(); } public void step() { this.redDot.step(); this.blueDot.step(); } public void showStatus() { this.redDot.showPosition(); this.blueDot.showPosition(); } public void reset() { this.redDot.reset(); this.blueDot.reset(); } using the Dot class, a DotRace class is straightforward fields store the two Dots constructor creates the Dot objects, initializing their colors and max steps methods utilize the Dot methods to produce the race behaviors CREATE AND PLAY ADD ANOTHER DOT?

9 Adding a finish line suppose we wanted to place a finish line on the race what changes would we need? could add a field to store the goal distance user specifies goal distance along with max step size in constructor call step method would not move if either dot has crossed the finish line public class DotRace { private Dot redDot; private Dot blueDot; private int goalDistance; // distance to the finish line public DotRace(int goal) { this.redDot = new Dot("red"); this.blueDot = new Dot("blue"); this.goalDistance = goal; } public int getGoalDistance() { return this.goalDistance; }...

10 Checking the finish line to run a step of the race, really need to consider 3 possibilities RED has crossed the finish line BLUE has crossed the finish line neither has crossed, so the race must continue recall: a simple if statement is a 1-way conditional ( execute this or not ) if (this.redDot.getPosition() >= this.goalDistance) { System.out.println("The race is over!"); } an if statement with else case is a 2-way conditional ( execute this or that ) if (this.redDot.getPosition() >= this.goalDistance) { System.out.println("The race is over!"); } else { // HANDLE THE CASE WHERE RED HASN'T CROSSED } here, the case where RED hasn't crossed must be broken into cases (BLUE has crossed, or not)

11 Multi-way conditionals can get a multi-way conditional by nesting if statements public void step() { if (this.redDot.getPosition() >= this.goalDistance) { System.out.println("The race is over!"); } else { if (this.blueDot.getPosition() >= this.goalDistance) { System.out.println("The race is over!"); } else { this.redDot.step(); this.blueDot.step(); } in fact, you can handle an arbitrary number of cases by nesting ifs deep nesting can lead to ugly code, however

12 Cascading if-else to make nested if statements look nicer, some curly-braces can be omitted and the cases indented to show structure public void step() { if (this.redDot.getPosition() >= this.goalDistance) { System.out.println("The race is over!"); } else if (this.blueDot.getPosition() >= this.goalDistance) { System.out.println("The race is over!"); } else { this.redDot.step(); this.blueDot.step(); } such a structure is known as a cascading if-else control cascades down the cases like water cascading down a waterfall if a test fails, control moves down to the next one if (TEST_1) { STATEMENTS_1; } else if (TEST_2) { STATEMENTS_2; } else if (TEST_3) { STATEMENTS_3; }... else { STATEMENTS_ELSE; }

13 Combining cases this code works, but contains redundancy there are two cases that result in the same code! public void step() { if (this.blueDot.getPosition() >= this.goalDistance) { System.out.println("The race is over!"); } else if (this.redDot.getPosition() >= this.goalDistance) { System.out.println("The race is over!"); } else { this.redDot.step(); this.blueDot.step(); } fortunately, Java provides logical operators for simplifying such cases (TEST1 || TEST2) evaluates to true if either TEST1 OR TEST2 is true (TEST1 && TEST2) evaluates to true if either TEST1 AND TEST2 is true (!TEST) evaluates to true if TEST is NOT true

14 Logical operators here, could use || to avoid duplication print message if either blue or red has crossed the finish line public void step() { if (this.redDot.getPosition() >= this.goalDistance || this.blueDot.getPosition() >= this.goalDistance) { System.out.println("The race is over!"); } else { this.redDot.step(); this.blueDot.step(); } note: we could have easily written step using && move dots if both blue and red dots have failed to cross finish line public void step() { if (this.redDot.getPosition() < this.goalDistance && this.blueDot.getPosition() < this.goalDistance) { this.redDot.step(); this.blueDot.step(); } else { System.out.println("The race is over!"); } warning: the tests that appear on both sides of || and && must be complete Boolean expressions (x == 2 || x == 12) OK (x == 2 || 12) BAD!

15 EXERCISE how would we change step if we wanted to display the winner? RED wins! BLUE wins! It's a tie! public void step() { if ( ??? ) {. } else { this.redDot.step(); this.blueDot.step(); }

16 Modularity and scope key idea: independent modules can be developed independently in the real world, a software project might get divided into several parts each part is designed & coded by a different team, then integrated together internal naming conflicts should not be a problem e.g., when declaring a local variable in a method, the programmer should not have to worry about whether that name is used elsewhere in Java, all variables have a scope (i.e., a section of the program where they exist and can be accessed) the scope of a field is the entire class (i.e., all methods can access it) the scope of a parameter is its entire method the scope of a local variable is from its declaration to the end of its method so, you can use the same name as a local variable/parameter in multiple methods you can also use the same field name in different classes in fact, different classes may have methods with the same name!

17 If statements and scope the curly braces associated with if statements also define new scopes a variable declared inside an if case is local to that case memory is allocated for the variable only if it is reached when that case is completed, the associated memory is reclaimed public double giveChange() { if (this.payment >= this.purchase) { double change = this.payment – this.purchase; this.purchase = 0; this.payment = 0; return change; } else { System.out.println("Enter more money first."); return 0.0; } if the test fails, then the declaration is never reached and the effort of creating & reclaiming memory is saved also, cleaner since the variable is declared close to where it is needed