1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.

Slides:



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

Logic & program control part 2: Simple selection structures.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
CS 106 Introduction to Computer Science I 01 / 30 / 2008 Instructor: Michael Eckmann.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Mathematical Operators: working with floating point numbers and more operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
CS 106 Introduction to Computer Science I 09 / 18 / 2006 Instructor: Michael Eckmann.
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
Expressions, Data Conversion, and Input
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 11 Conditional.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
CPS120: Introduction to Computer Science Operations Lecture 9.
Mathematical Calculations in Java Mrs. G. Chapman.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
ITM © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings.
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.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
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 2009 Conditionals, expressions & modularization  if statements, if-else  increment/decrement, arithmetic assignments.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Mathematical Calculations in Java Mrs. C. Furman.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Advanced Arithmetic, Conditionals, and Loops INFSY 535.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
1 CSC 221: Computer Programming I Fall 2011 Python control statements  operator precedence  importing modules  random, math  conditional execution:
1 CSC 221: Computer Programming I Spring 2010 Conditionals, expressions & modularization  if statements, if-else  increment/decrement, arithmetic assignments.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Week 12 - Monday.  What did we talk about last time?  Defining classes  Class practice  Lab 11.
What are Operators? Some useful operators to get you started.
Java-02 Basic Concepts Review concepts and examine how java handles them.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
1 CSC 221: Computer Programming I Fall 2005 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
1 09/10/04CS150 Introduction to Computer Science 1 What Actions Do We Have Part 2.
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.
CompSci 230 S Programming Techniques
Chapter 7: Expressions and Assignment Statements
Lecture 3 Java Operators.
2.5 Another Java Application: Adding Integers
Chapter 7: Expressions and Assignment Statements
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Primitive Data, Variables, Loops (Maybe)
ITM 352 Expressions, Precedence, Working with Strings Class #5
Type Conversion, Constants, and the String Object
OPERATORS (1) CSC 111.
OPERATORS (2) CSC 111.
Increment and Decrement
Expressions and Assignment
Data Types and Expressions
Chapter 2 Programming Basics.
Primitive Types and Expressions
Problem 1 Given n, calculate 2n
Data Types and Expressions
Data Types and Expressions
Presentation transcript:

1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments  mixed expressions  type casting  operator precedence  mixing numbers and Strings

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) { purchase = 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) { purchase = 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 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 a negative amount public void recordPurchase(double amount) { if (amount > 0) { purchase = 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 = payment - purchase; purchase = 0; 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?

8 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) { purchase += amount; } else { System.out.println("ILLEGAL PURCHASE"); }

9 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

10 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() { numSides = 6; numRolls = 0; rollTotal = 0; } public Die(int sides) { numSides = sides; numRolls = 0; rollTotal = 0; } public int getNumberOfSides() { return numSides; } public int getNumberOfRolls() { return numRolls; } public double getAverageOfRolls() { return rollTotal/numRolls; } public int roll() { numRolls++; int currentRoll = (int)(Math.random()*getNumberOfSides() + 1); 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

11 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() { numSides = 6; numRolls = 0; rollTotal = 0; } public Die(int sides) { numSides = sides; numRolls = 0; rollTotal = 0; } public int getNumberOfSides() { return numSides; } public int getNumberOfRolls() { return numRolls; } public double getAverageOfRolls() { return (double)rollTotal/numRolls; } public int roll() { numRolls++; int currentRoll = (int)(Math.random()*getNumberOfSides() + 1); 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

12 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)

13 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));