itm352 conditionals lecture #5. 1/28/03itm352 fall 2003 class 5 – control flow 2 announcements r...
Post on 20-Dec-2015
212 views
TRANSCRIPT
ITM352ConditionalsLecture #5
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 2
Announcements Assignment 1
Create a Zip file of your JBuilder project directory (the folder that contains the .jpr or .jpx file, your source code, etc.) and email it as an attachment to [email protected]
If you don’t know how to create a Zip file or email an attachment ask a friend or contact me
Assignment 1 is due by 11:59pm TONIGHT ** beware ** I use a very sophisticated program that checks to see if your
code is the same as another's. It cannot be easily fooled by just changing the names of variables or moving lines around.
Short, in class quizzes will start TODAY Mostly on terminology Will be easy if you have been paying attention You may not get a quiz every class
Lab class dates have changed!!! Check the “Weekly Schedule” for details Go to E 102, NOT this classroom!!!
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 3
Announcements (cont.) The “last of the last minute man” homework curse
continues…. DO NOT PUT OFF PROGRAMMING ASSIGNMENTS
TO THE DAY THEY ARE DUE!!!! It’s far too risky, too many things can go wrong.
I VERY strongly recommend you always test and review anything that is given out to you (homework, examples, etc.) and anything you submit Get in the habit of compiling and testing your code as you write it Be generous with your code comments (you are never penalized
for too many comments)
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 4
** Important Notice **
Section 2 On 2/4, 2/6, 2/11 please go to the section 1
lecture from 12:00-1:15pm, there will be no 1:30-2:45pm lecture on those dates
If you absolutely cannot make these lectures, come see me RIGHT AWAY
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 5
Today
Review Basic Java Program Variables, types, casting SavitchIn I/O
Documentation and Coding StyleControl Flow
Conditionals (decisions) Loops <if time>
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 6
Review
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 7
Basic Java Program Structure
public class MyClass {
public static void main (String args[]) {
<your code here>
} // end of main method
} // end of MyClass def
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 8
Types: Which Ones to Know for Now
int just whole numbers may be positive or negative no decimal point
char just a single character uses single quotes for examplechar letterGrade = `A`;
double real numbers, both positive and
negative has a decimal point (fractional
part) two formats
number with decimal point, e.g. 514.061
e (or scientific, or floating-point) notation, e.g. 5.14061 e2, which means 5.14061 x 102
boolean two values “true” or “false”
Display in text is for reference; for now stick to these simple primitive types:
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 9
Specialized Assignment Operators
A shorthand notation for performing an operation on and assigning a new value to a variable
General form: var <op>= expression; equivalent to: var = var <op> (expression); <op> is +, -, *, /, or %
Examples:
amount += 5;
//amount = amount + 5;
amount *= 1 + interestRate;
//amount = amount * (1 + interestRate); Note that the right side is treated as a unit (put parentheses around the entire
expression)
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 10
Returned Value Expressions return values: the number produced by an
expression is “returned”, i.e. it is the “return value.”int numberOfBaskets, eggsPerBasket, totalEggs;
numberOfBaskets = 5;
eggsPerBasket = 8;
totalEggs = numberOfBaskets * eggsPerBasket; in the last line numberOfBaskets returns the value 5 and eggsPerBasket returns the value 8
numberOfBaskets * eggsPerBasket is an expression that returns the integer value 40
Similarly, methods return valuesSavitchIn.readLine(); is a method that returns a string read
from the keyboard
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 11
Explicit casting is required to assign a higher type to a lower
ILLEGAL: Implicit casting to a lower data type
int n;
double x = 2.1;
n = x;//illegal in java
It is illegal since x is double, n is an int, and double is a higher data type than integer
LEGAL: Explicit casting to a lower data type int n;
double x = 2.1;
n = (int)x;//legal in java You can always use an explicit cast where an implicit one will be done
automatically, but it is not necessary
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 12
Truncation When Casting a doubleto an Integer
Converting (casting) a double to integer does not round; it truncates the fractional part is lost (discarded, ignored, thrown away)
For example:
int n;
double x = 2.99999;
n = (int)x;//cast is required, x is truncated the value of n is now 2
This behavior is useful for some calculations, as demonstrated in Case Study: Vending Machine Change
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 13
Examples of Expressions
Ordinary MathExpression
Java Expression(preferred form)
Java FullyParenthesizedExpression
rate2 + delta rate*rate + delta (rate*rate) + delta
2(salary + bonus) 2 * (salary + bonus) 2 * (salary + bonus)
3mass time
1
1/(time + 3 * mass) 1/(time + (3 * mass))
9v t
7 - a
(a - 7) / (t + 9 * v) (a - 7) / (t +( 9 * v))
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 14
Increment and Decrement Operators
Shorthand notation for common arithmetic operations on variables used for counting
Some counters count up, some count down, but they are integer variables The counter can be incremented (or decremented) before or after using its
current value
int count;
…
++count preincrement count: count = count + 1 before using it
count++ postincrement count: count = count + 1 after using it
--count predecrement count: count = count -1 before using it
count-- postdecrement count: count = count -1 after using it
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 15
Indexing Characters within a String The index of a character is the position of a character within a string Strings are 0 based meaning the first index is at position 0. The charAt(Position)method returns the char at the specified
position substring(Start, End)method returns the string from position
Start to position End For example:
String greeting = "Hi, there!";greeting.charAt(0)returns Hgreeting.charAt(2)returns ,greeting.substring(4,6)returns “th”
H i , t h e r e !
0 1 2 3 4 5 6 7 8 9
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 16
More String Methods
length() equals(Other_String) equalsIgnoreCase(Other_String) toLowerCase() toUpperCase() charAt(position) substring(Start) substring(Start, End) indexOf(Other_String) indexOf(Other_String, Start)
See pp. 82-83 for more details!
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 17
Concatenating (Appending) StringsThe + operator is used for string concatenation (merging two strings):
String name = "Mondo";String greeting = "Hi, there!";System.out.println(greeting + name + "Welcome");causes the following to display on the screen:>Hi, there!MondoWelcome> Note that you have to remember to include spaces if you want it to look
right:System.out.println(greeting + " " + name + " Welcome"); causes the following to display on the screen:>Hi, there! Mondo Welcome>
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 18
I/O Classes
We have been using an output method from a class that automatically comes with Java:
System.out.println() But Java does not automatically have an input class, so one must be added
SavitchIn is a class specially written to do keyboard input SavitchIn.java is provided with the text - see Appendix 2 Examples of SavitchIn methods for keyboard input:
readLineInt()readLineDouble()readLineNonwhiteChar()
Gotcha: remember Java is case sensitive, for example readLineNonWhiteChar()will not work
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 19
End of Review
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 20
Documentation and Style
Use meaningful names for variables, classes, etc. Use indentation and line spacing as shown in the examples
in the text Always include a “prologue” (an brief explanation of the
program at the beginning of the file) Use all lower case for variables, except capitalize internal
words (eggsPerBasket) Use all upper case for variables that have a constant value, PI for the value of pi (3.14159…) (see text for more examples)
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 21
Comments
Comment—text in a program that the compiler ignores Does not change what the program does, only explains the program Write meaningful and useful comments Comment the non-obvious Assume a reasonably knowledgeable reader // for single-line comments /* … */ for multi-line comments Two kinds of comments: inside or outside of a block Comments outside of a block explain what the block of code does
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 22
Indentation
Codes inside a block should be indented.Indent 2 to 4 spacesBe consistent.
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 23
Named Constants
Named constant—using a name instead of a value Example: use TAX_RATE instead of 5.25 Advantages of using named constants
Easier to understand program because reader can tell how the value is being used
Easier to modify program because value can be changed in one place (the definition) instead of being changed everywhere in the program.
Avoids mistake of changing same value used for a different purpose
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 24
Defining Named Constants
public—has public visibility. There are no restrictions on where this name can be used
static—must be included, but explanation has to waitfinal—the program is not allowed to change the value The remainder of the definition is similar to a variable
declaration and gives the type, name, and initial value. A declaration like this is usually at the beginning of the
file and is not inside the main method definition.
public static final double PI = 3.14159;
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 25
Chapter 3
BranchingLoopsexit(n) methodBoolean data type and
expressions
Flow of Control
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 26
What is “Flow of Control”? Flow of Control is the execution order of instructions in a
program All programs can be written with three control flow
elements:1. Sequence - just go to the next instruction2. Selection - a choice of at least two
either go to the next instruction or jump to some other instruction
3. Repetition - a loop (repeat a block of code) at the end of the loop
either go back and repeat the block of code or continue with the next instruction after the block
Selection and Repetition are called Branching since these are branch points in the flow of control
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 27
Java Flow Control Statements
Sequence the defaultJava automatically
executes the next instruction unless you use a branching statement
Branching: Selection if if-else if-else if-else if- … - else
switch
Branching: Repetition while do-while for
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 28
Definition of Boolean Values Branching: there is more than one choice for the next
instruction Which branch is taken depends on a test condition which
evaluates to either true or false In general:
if test is true then do this, otherwise it is false, do something else
Variables (or expressions) that are either true or false are called boolean variables (or expressions)
So the value of a boolean variable (or expression) is eithertrue or false
boolean is a primitive data type in Java
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 29
Boolean Expressions Boolean expressions can be thought of as test
conditions (questions) that are either true or false Often two values are compared For example:
Is A greater than B?Is A equal to B?Is A less than or equal to B?etc.
A and B can be any data type (or class), but they should be the same data type (or class)
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 30
Java Comparison Operators
Math Notation
Name
Java Notation
Java Examples
= equal to == balance == 0 answer == 'y'
not equal to != income != tax answer != 'y'
> greater than
> income > outgo
greater than or equal to
>= points >= 60
< less than
< pressure < max
less than or equal to <= income <= outgo
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 31
Comparing objects Great care must be taken when comparing objects:
Statements like myRobot == theRobot compare references to where the objects are stored, not the objects themselves!
In general the equals() method is used The objects themselves define what it means for objects to be
equal
myRobot theRobot
myRobot == theRobotis false
aRobot
theRobot == aRobotis true
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 32
Example: Comparison Methods forString Class
“==“ does not do what you may think for String objects When “==“ is used to test objects (such as String objects) it tests to
see if the storage addresses of the two objects are the same are they stored in the same location? more will be said about this later
Use “.equals” method to test if the strings, themselves, are equalString s1 = “Mondo”;String s2;s2 = SavitchIn.readLine();//s1.equals(s2) returns true if the user enters Mondo, false
otherwise .equals()is case sensitive Use .equalsIgnoreCase()to ignore case
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 33
Compound Boolean Expressions Use && to AND two or more conditions Use || to OR two or more conditions See text for definitions of AND and OR For example, write a test to see if B is either 0 or between
the values of B and C :(B == 0) || (A <= B && B < C)
In this example the parentheses are not required but are added for clarity See text (and later slides) for Precedence rules Note the short-circuit, or lazy, evaluation rules in text (and later in
slides) Use a single & for AND and a single | for OR to avoid short-
circuit evaluation and force complete evaluation of a boolean expression
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 34
Java if statement
Simple decisions Do the next statement if test is true or skip it if
false Syntax:
if (Boolean_Expression)
Action if true;//execute if true
next action;//always executed
Note the indentation for readability (not compile or execution correctness)
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 35
if Example
The body of the if statement is conditionally executed
Statements after the body of the if statement always execute
if(eggsPerBasket < 12)
//begin body of the if statement
System.out.println(“Less than a dozen eggs per basket”);
//end body of the if statement
totalEggs = numberOfEggs * eggsPerBasket;
System.out.println(“You have a total of
+ totalEggs + “ eggs.”);
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 36
Java Statement Blocks:Compound Statements
Action if true can be either a single Java statement or a set of statements enclosed in curly brackets (a compound statement, or block)
For example:
if(eggsPerBasket < 12){ //begin body of the if statement System.out.println(“Less than a dozen ...”); costPerBasket = 1.1 * costPerBasket} //end body of the if statement
totalEggs = numberOfEggs * eggsPerBasket;System.out.println(“You have a total of “ + totalEggs + “ eggs.”);
All statements between braces are controlled by if
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 37
Two-way Selection: if-else Select either one of two options Either do Action1 or Action2, depending on test value Syntax:
if (Boolean_Expression)
{
Action1 //execute only if true
}
else
{
Action2//execute only if false
}
Action3//always executed
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 38
if-else Examples
Example with single-statement blocks:if(time < limit) System.out.println(“You made it.”);else
System.out.println(“You missed the deadline.”);
Example with compound statements:
if(time < limit){ System.out.println(“You made it.”); bonus = 100;}else{ System.out.println(“You missed the deadline.”); bonus = 0;}
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 39
Multibranch selection:if-else if-else if-…-else
One way to handle situations with more than two possibilities
Syntax:if(Boolean_Expression_1) Action_1else if(Boolean_Expression_2) Action_2 . . .else if(Boolean_Expression_n) Action_nelse Default_Action
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 40
if-else if-else if-…-else Example
if(score >= 90 && score <= 100)
grade = ‘A’);
else if (score >= 80)
grade = ‘B’;
else if (score >= 70)
grade = ‘C’;
else if (score >= 60)
grade = ‘D’;
else
grade = ‘E’;
Note how the sequence is important here and must use else if rather than just if (why?)
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 41
if-else if-else if-…-else Non-Example??
if (profRel.equals(“colleague”) ) greeting = “Daniel”;else if (profRel.equals(“friend”) ) greeting = “Dan”;else if (profRel.equals(“grad student”) ) greeting = “DP”;else if (profRel.equals(“undergrad student”) ) greeting = “Professor”;else
greeting = “Mr. Port”;
1/28/03 ITM352 Fall 2003 Class 5 – Control Flow 42
Quiz #1 – 5 points (5 mins)
Name: _____________ID #: ______________
1) Write a Java statement that declares a variable of type float named birthYear and initialize it with the year of your birth (explicitly cast your birth year value appropriately)
2) Write out a complete Java program (with class definition, main method, comments, proper coding style, etc.) that prints “I was born in the year” and concatenates it with the variable birthYear
3) Write a compound conditional expression with a type boolean return value of true when a string lastName is your last name and birthYear is greater or equal to 1982.