1 CSC 221: Computer Programming I Spring 2010 Conditionals, expressions & modularization  if statements, if-else  increment/decrement, arithmetic assignments.

Slides:



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

1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
Introduction to C Programming
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Introducing Algorithms, Pseudocode and.
CS 106 Introduction to Computer Science I 01 / 30 / 2008 Instructor: Michael Eckmann.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Introduction to C Programming
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Fundamentals of Python: From First Programs Through Data Structures
1 CSC 221: Computer Programming I Fall 2004 Objects and classes: a first pass  software objects, classes, object-oriented design  BlueJ IDE, compilation.
Expressions, Data Conversion, and Input
1 CSC 222: Object-Oriented Programming Spring 2013 interacting objects  abstraction, modularization  internal vs. external method calls  expressions,
Fundamentals of Python: First Programs
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Wage Calculator Application: Introducing.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Input, Output, and Processing
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Conditional Execution
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 11 Conditional.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
1 CSC 221: Computer Programming I Spring 2010 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
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.
1 CSC 221: Computer Programming I Spring 2008 Objects and classes: a broad view  software objects, classes, object-oriented design  BlueJ IDE, compilation.
1 CSC 222: Object-Oriented Programming Spring 2013 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
1 CSC 221: Computer Programming I Fall 2006 Conditionals, expressions & modularization  if statements, if-else  increment/decrement, arithmetic assignments.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 CSC 221: Computer Programming I Fall 2004 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
1 CSC 221: Computer Programming I Fall 2009 Conditionals, expressions & modularization  if statements, if-else  increment/decrement, arithmetic assignments.
Chapter 4 Introduction to Classes, Objects, Methods and strings
1 A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 4 JavaScript and.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Java-02 Basic Concepts Review concepts and examine how java handles them.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 CSC 221: Computer Programming I Fall 2005 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
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.
CSC 222: Object-Oriented Programming Fall 2015
COMP 170 – Introduction to Object Oriented Programming
Building Java Programs
Java Primer 1: Types, Classes and Operators
Assignment and Arithmetic expressions
Primitive Data, Variables, Loops (Maybe)
Chapter 4 Control Statements: Part I
Building Java Programs
Building Java Programs Chapter 2
Expressions and Assignment
Chapter 2 Programming Basics.
Chapter 3: Selection Structures: Making Decisions
Building Java Programs
CSC 221: Computer Programming I Spring 2008
Java Programming Language
Building Java Programs
Chapter 11 Conditional Execution
Building Java Programs Chapter 2
Building Java Programs
Computers and Scientific Thinking David Reed, Creighton University
Presentation transcript:

1 CSC 221: Computer Programming I Spring 2010 Conditionals, expressions & modularization  if statements, if-else  increment/decrement, arithmetic assignments  mixed expressions  type casting  abstraction, modularization  internal vs. external method calls  primitives vs. objects

2 Conditional execution so far, all of the statements in methods have executed unconditionally  when a method is called, the statements in the body are executed in sequence  different parameter values may produce different results, but the steps are the same many applications require conditional execution  different parameter values may cause different statements to be executed example: consider the CashRegister class  previously, we assumed that method parameters were "reasonable" i.e., user wouldn't pay or purchase a negative amount user wouldn't check out unless payment amount ≥ purchase amount  to make this class more robust, we need to introduce conditional execution i.e., only add to purchase/payment total IF the amount is positive only allow checkout IF payment amount ≥ purchase amount

3 If statements in Java, an if statement allows for conditional execution  i.e., can choose between 2 alternatives to execute if (perform some test) { Do the statements here if the test gave a true result } else { Do the statements here if the test gave a false result } public void recordPurchase(double amount) { if (amount > 0) { this.purchase = this.purchase + amount; } else { System.out.println("ILLEGAL PURCHASE"); } } if the test evaluates to true (amount > 0), then this statement is executed otherwise (amount <= 0), then this statement is executed to alert the user

4 If statements (cont.) you are not required to have an else case to an if statement  if no else case exists and the test evaluates to false, nothing is done  e.g., could have just done the following public void recordPurchase(double amount) { if (amount > 0) { this.purchase = this.purchase + amount; } but then no warning to user if a negative amount were entered (not as nice) standard relational operators are provided for the if test greater than = greater than or equal to == equal to != not equal to && AND || OR ! NOT a comparison using a relational operator is known as a Boolean expression, since it evaluates to a Boolean ( true or false ) value

5 In-class exercises update recordPurchase to display an error message if attempt to purchase a negative or zero amount public void recordPurchase(double amount) { if (amount > 0) { this.purchase = this.purchase + amount; } else { System.out.println("ILLEGAL PURCHASE"); } similarly, update enterPayment

6 In-class exercises what changes should be made to giveChange ? public double giveChange() { if ( ) { double change = this.payment – this.purchase; this.purchase = 0; this.payment = 0; return change; } else { } note: if a method has a non-void return type, every possible execution sequence must result in a return statement  the Java compiler will complain otherwise

7 A further modification suppose we wanted to add to the functionality of CashRegister  get the number of items purchased so far  get the average cost of purchased items ADDITIONAL FIELDS? CHANGES TO CONSTRUCTOR? NEW METHODS?

Cascading if-else an if-else allows you to distinguish among two alternatives  if the test succeeds, execute the statements in the if-case  otherwise, execute the statements in the else-case 8 if (avg < 60) { return "FAIL"; } else { return "PASS"; } if more than two alternatives, you can nest if-else statements  e.g., break the else-case into sub-cases  known as a cascading if-else (control cascades down from one test to the next) if (avg < 60) { return "FAIL"; } else { if (avg < 70) { return "PASS – NO TRANSFER"; } else { return "PASS"; } some redundant curly-braces can be removed to make cascading if-else cleaner  each case lines up, indents evenly if (avg < 60) { return "FAIL"; } else if (avg < 70) { return "PASS – NO TRANSFER"; } else { return "PASS"; }

HW 3: GradeCalculator want to be able to  enter a sequence of grades  keep track of the lowest grade so far  determine the average of entered grades o if no grades, average is 0.0 o if at least 5 grades, drop the lowest  determine the corresponding letter grade (90+ is "A", 80+ is "B", etc.) 9

10 Shorthand assignments a variable that is used to keep track of how many times some event occurs is known as a counter  a counter must be initialized to 0, then incremented each time the event occurs  incrementing (or decrementing) a variable is such a common task that Java that Java provides a shorthand notation number++; is equivalent to number = number + 1; number--; is equivalent to number = number - 1; other shorthand assignments can be used for updating variables number += 5; ≡ number = number + 5; number -= 1; ≡ number = number - 1; number *= 2; ≡ number = number * 2;number /= 10; ≡ number = number / 10; public void recordPurchase(double amount) { if (amount > 0) { this.purchase += amount; } else { System.out.println("ILLEGAL PURCHASE"); }

11 Mixed expressions note that when you had to calculate the average purchase amount, you divided the purchase total ( double ) with the number of purchases ( int )  mixed arithmetic expressions involving doubles and ints are acceptable  in a mixed expression, the int value is automatically converted to a double and the result is a double   / 4  / 4.0  / 2.0  2.5  however, if you apply an operator to two ints, you always get an int result  / 4  30 5 / 3  2 ??? CAREFUL: integer division throws away the fraction

12 Die revisited extend the Die class to keep track of the average roll  need a field to keep track of the total  initialize the total in the constructors  update the total on each roll  compute the average by dividing the total with the number of rolls public class Die { private int numSides; private int numRolls; private int rollTotal; public Die() { this.numSides = 6; this.numRolls = 0; this.rollTotal = 0; } public Die(int sides) { this.numSides = sides; this.numRolls = 0; this.rollTotal = 0; } public int getNumberOfSides() { return this.numSides; } public int getNumberOfRolls() { return this.numRolls; } public double getAverageOfRolls() { return this.rollTotal/this.numRolls; } public int roll() { this.numRolls++; int currentRoll = (int)(Math.random()*this.numSides + 1); this.rollTotal += currentRoll; return currentRoll; } PROBLEM: since rollTotal and numRolls are both ints, integer division will be used avg of 1 & 2 will be 1 UGLY SOLUTION: make rollTotal be a double kludgy! it really is an int

13 Type casting a better solution is to keep rollTotal as an int, but cast it to a double when needed  casting tells the compiler to convert from one compatible type to another  general form: (NEW_TYPE)VALUE  if rollTotal is 3, the expression (double)rollTotal evaluates to 3.0 public class Die { private int numSides; private int numRolls; private int rollTotal; public Die() { this.numSides = 6; this.numRolls = 0; this.rollTotal = 0; } public Die(int sides) { this.numSides = sides; this.numRolls = 0; this.rollTotal = 0; } public int getNumberOfSides() { return this.numSides; } public int getNumberOfRolls() { return this.numRolls; } public double getAverageOfRolls() { return (double)this.rollTotal/this.numRolls; } public int roll() { this.numRolls++; int currentRoll = (int)(Math.random()*this.numSides + 1); this.rollTotal += currentRoll; return currentRoll; } you can cast in the other direction as well (from a double to an int) any fractional part is lost if x is 3.7  (int)x evaluates to 3 what if you call getAverageOfRolls before rolling the die?

14 Complex expressions how do you evaluate an expression like * 3 and 8 / 4 / 2 Java has rules that dictate the order in which evaluation takes place  * and / have higher precedence than + and –, meaning that you evaluate the part involving * or / first * 3  1 + (2 * 3)   7  given operators of the same precedence, you evaluate from left to right 8 / 4 / 2  (8 / 4) / 2  2 / 2  – 1  (3 + 2) – 1  5 – 1  4 GOOD ADVICE: don't rely on these (sometimes tricky) rules  place parentheses around sub-expressions to force the desired order (3 + 2) – 13 + (2 – 1)

15 Mixing numbers and Strings recall that the + operator can apply to Strings as well as numbers  when + is applied to two numbers, it represents addition:  5  when + is applied to two Strings, it represents concatenation: "foo" + "bar"  "foobar"  what happens when it is applied to a String and a number? when this occurs, the number is automatically converted to a String (by placing it in quotes) and then concatenation occurs x = 12; System.out.println("x = " + x);  be very careful with complex mixed expressions System.out.println("the sum is " ); System.out.println( " is the sum");  again, use parentheses to force the desired order of evaluation System.out.println("the sum is " + (5 + 2));

16 Abstraction abstraction is the ability to ignore details of parts to focus attention on a higher level of a problem  note: we utilize abstraction everyday do you know how a TV works? could you fix one? build one? do you know how an automobile works? could you fix one? build one? abstraction allows us to function in a complex world  we don't need to know how a TV or car works  must understand the controls (e.g., remote control, power button, speakers for TV) (e.g., gas pedal, brakes, steering wheel for car)  details can be abstracted away – not important for use the same principle applies to programming  we can take a calculation/behavior & implement as a method after that, don't need to know how it works – just call the method to do the job  likewise, we can take related calculations/behaviors & encapsulate as a class

17 Abstraction examples recall the Die class  included the method roll, which returned a random roll of the Die do you remember the formula for selecting a random number from the right range? WHO CARES?!? Somebody figured it out once, why worry about it again? SequenceGenerator class  included the method randomSequence, which returned a random string of letters you don't know enough to code it, but you could use it! Circle, Square, Triangle classes  included methods for drawing, moving, and resizing shapes again, you don't know enough to code them, but you could use them!

18 Modularization modularization is the process of dividing a whole into well-defined parts, which can be built and examined separately, and which interact in well- defined ways  early computers were hard to build – started with lots of simple components (e.g., vacuum tubes or transistors) and wired them together to perform complex tasks  today, building a computer is relatively easy – start with high-level modules (e.g., CPU chip, RAM chips, hard drive) and plug them together think Garanimals! the same advantages apply to programs  if you design and implement a method to perform a well-defined task, can call it over and over within the class  likewise, if you design and implement a class to model a real-world object's behavior, then you can reuse it whenever that behavior is needed (e.g., Die for random values)

19 Code reuse can occur within a class one method can call another method (a.k.a. an internal method call )  a method call consists of "this." + method name + any parameter values in parentheses (as shown in BlueJ when you right-click and select a method to call) this.MethodName(paramValue1, paramValue2, …);  calling a method causes control to shift to that method, executing its code  if the method returns a value (i.e., a return statement is encountered), then that return value is substituted for the method call where it appears public class Die {... public int getNumberOfSides() { return this.numSides; } public int roll() { this.numRolls = this.numRolls + 1; return (int)(Math.random()*this.getNumberOfSides() + 1); } here, could call the getNumberOfSides accessor method to get the # of sides

20 e.g., Singer class public class Singer {... public void oldMacDonaldVerse(String animal, String sound) { System.out.println("Old MacDonald had a farm, E-I-E-I-O."); System.out.println("And on that farm he had a " + animal + ", E-I-E-I-O"); System.out.println("With a " + sound + "-" + sound + " here, and a " + sound + "-" + sound + " there, "); System.out.println(" here a " + sound + ", there a " + sound + ", everywhere a " + sound + "-" + sound + "."); System.out.println("Old MacDonald had a farm, E-I-E-I-O."); System.out.println(); } public void oldMacDonaldSong() { this.oldMacDonaldVerse("cow", "moo"); this.oldMacDonaldVerse("duck", "quack"); this.oldMacDonaldVerse("sheep", "baa"); this.oldMacDonaldVerse("dog", "woof"); }... } when the method has parameters, the values specified in the method call are matched up with the parameter names by order the parameter variables are assigned the corresponding values these variables exist and can be referenced within the method they disappear when the method finishes executing the values in the method call are sometimes referred to as input values or actual parameters the parameters that appear in the method header are sometimes referred to as formal parameters

21 Creating/manipulating objects in BlueJ so far, we have created objects in BlueJ by right-clicking on the class icon  e.g., when you select either new Die() or new Die(int numSides ) BlueJ calls the specified constructor and prompts you for any parameter values similarly, we have called methods by right-clicking on the object icon  e.g., when you select int roll() BlueJ calls the specified method

BlueJ’s code pad BlueJ’s hands-on manipulation is nice can also do things the old-fashioned way in the code pad 22 to call a method on an object: OBJECT.METHOD(PARAMS) e.g., die1.roll() can even create an object in the code pad: CLASS OBJECT = new CLASS(PARAMS); e.g., Die die2 = new Die();

23 Creating objects in code why bother with the code pad?  it demonstrates the format we must use for creating and manipulating objects from within other classes e.g., we might want to define a class that uses a Die object Die d6 = new Die();// constructs a Die object named d6, // initialized using the default // constructor Die d8 = new Die(8);// constructs a Die object named d8, // initialized using single parameter // constructor System.out.println(d6.roll()); // calls the roll method on the Die // object named d6, displays the result System.out.println(d8.getNumberOfSides()); // calls the getNumberOfSides method on // the Die object named d8, displays the // result  calling a method on a different object (e.g., a field or local variable) is known as an external method call

24 Example: Decider public class Decider { private Die die; /** * Constructs a Decider object. */ public Decider() { this.die = new Die(2); } /** * Answers a yes/no type of question. question the question being asked either "YES" or "NO" */ public String decide(String question) { if (this.die.roll() == 1) { return "YES"; } else { return "NO"; } consider a class for randomly making a yes/no decision  could choose between the two alternatives using Math.random()  better, use the Die abstraction to create a 2-sided die the class has a Die field (BlueJ shows class dependencies with dotted lines) the Die field is initialized in the constructor the Die field is then rolled and compared in the method

25 Example: Face public class Face { private Circle head; private Circle leftEye; private Circle rightEye; private Triangle mouth; /** * Constructor for objects of class Face */ public Face() { this.head = new Circle(); this.head.changeSize(100); this.head.changeColor("yellow"); this.leftEye = new Circle(); this.leftEye.changeSize(10); this.leftEye.changeLoc(50,90); this.rightEye = new Circle(); this.rightEye.changeSize(10); this.rightEye.changeLoc(80,90); this.mouth = new Triangle(); this.mouth.changeSize(-10, 50); this.mouth.changeLoc(70, 130); this.mouth.changeColor("red"); }... } recall the Face class, which automated drawing and moving a face  the class has fields for each of the shapes in the face  in the constructor, each shape is created by calling its constructor, assigning to the field, then calling methods to set properties

26 primitive types vs. object types internally, primitive (e.g., int, double) and object types are stored differently  when you inspect an object, any primitive fields are shown as boxes with values  when you inspect an object, any object fields are shown as pointers to other objects  of course, you can further inspect the contents of object fields we will consider the implications of primitives vs. objects later