Presentation is loading. Please wait.

Presentation is loading. Please wait.

ITM352 Conditionals Lecture #5. 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Assignment 1 m Create a Zip file of your JBuilder project.

Similar presentations


Presentation on theme: "ITM352 Conditionals Lecture #5. 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Assignment 1 m Create a Zip file of your JBuilder project."— Presentation transcript:

1 ITM352 Conditionals Lecture #5

2 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Assignment 1 m 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 dport@hawaii.edu m If you don’t know how to create a Zip file or email an attachment ask a friend or contact me m Assignment 1 is due by 11:59pm TONIGHT m ** 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. r Short, in class quizzes will start TODAY m Mostly on terminology m Will be easy if you have been paying attention m You may not get a quiz every class r Lab class dates have changed!!! m Check the “Weekly Schedule” for details m Go to E 102, NOT this classroom!!!

3 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 3 Announcements (cont.) r The “last of the last minute man” homework curse continues…. r DO NOT PUT OFF PROGRAMMING ASSIGNMENTS TO THE DAY THEY ARE DUE!!!! m It’s far too risky, too many things can go wrong. r I VERY strongly recommend you always test and review anything that is given out to you (homework, examples, etc.) and anything you submit m Get in the habit of compiling and testing your code as you write it m Be generous with your code comments (you are never penalized for too many comments)

4 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 4 ** Important Notice ** r Section 2 m 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 m If you absolutely cannot make these lectures, come see me RIGHT AWAY

5 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 5 Today r Review m Basic Java Program m Variables, types, casting m SavitchIn I/O r Documentation and Coding Style r Control Flow m Conditionals (decisions) m Loops

6 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 6 Review

7 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 7 Basic Java Program Structure public class MyClass { public static void main (String args[]) { } // end of main method } // end of MyClass def

8 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 8 Types: Which Ones to Know for Now r int m just whole numbers m may be positive or negative m no decimal point r char m just a single character m uses single quotes  for example char letterGrade = `A`; r double m real numbers, both positive and negative m has a decimal point (fractional part) m two formats r number with decimal point, e.g. 514.061 r e (or scientific, or floating- point) notation, e.g. 5.14061 e2, which means 5.14061 x 10 2 r boolean m two values “true” or “false” Display in text is for reference; for now stick to these simple primitive types:

9 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 9 Specialized Assignment Operators r A shorthand notation for performing an operation on and assigning a new value to a variable  General form: var = expression;  equivalent to: var = var (expression); m is +, -, *, /, or % r Examples: amount += 5; //amount = amount + 5; amount *= 1 + interestRate; //amount = amount * (1 + interestRate); r Note that the right side is treated as a unit (put parentheses around the entire expression)

10 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 10 Returned Value r 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 r Similarly, methods return values SavitchIn.readLine(); is a method that returns a string read from the keyboard

11 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 11 Explicit casting is required to assign a higher type to a lower r 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 r You can always use an explicit cast where an implicit one will be done automatically, but it is not necessary

12 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 12 Truncation When Casting a double to an Integer r Converting (casting) a double to integer does not round; it truncates m the fractional part is lost (discarded, ignored, thrown away) r For example: int n; double x = 2.99999; n = (int)x;//cast is required, x is truncated  the value of n is now 2 r This behavior is useful for some calculations, as demonstrated in Case Study: Vending Machine Change

13 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 13 Examples of Expressions

14 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 14 Increment and Decrement Operators r Shorthand notation for common arithmetic operations on variables used for counting r Some counters count up, some count down, but they are integer variables r 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

15 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 15 Indexing Characters within a String r The index of a character is the position of a character within a string r 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 r For example: String greeting = "Hi, there!"; greeting.charAt(0) returns H greeting.charAt(2) returns, greeting.substring(4,6) returns “th”

16 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 16 More String Methods r length() r equals(Other_String) r equalsIgnoreCase(Other_String) r toLowerCase() r toUpperCase() r charAt(position) r substring(Start) r substring(Start, End) r indexOf(Other_String) r indexOf(Other_String, Start) See pp. 82-83 for more details!

17 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 17 Concatenating (Appending) Strings The + 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 > m Note that you have to remember to include spaces if you want it to look right: System.out.println(greeting + " " + name + " Welcome"); m causes the following to display on the screen: >Hi, there! Mondo Welcome >

18 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 18 I/O Classes r We have been using an output method from a class that automatically comes with Java: System.out.println() r 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

19 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 19 End of Review

20 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 20 Documentation and Style r Use meaningful names for variables, classes, etc. r Use indentation and line spacing as shown in the examples in the text r 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)

21 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 21 Comments r Comment—text in a program that the compiler ignores r Does not change what the program does, only explains the program r Write meaningful and useful comments r Comment the non-obvious r Assume a reasonably knowledgeable reader  // for single-line comments  /* … */ for multi-line comments r Two kinds of comments: inside or outside of a block r Comments outside of a block explain what the block of code does

22 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 22 Indentation r Codes inside a block should be indented. r Indent 2 to 4 spaces r Be consistent.

23 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 23 Named Constants r Named constant—using a name instead of a value  Example: use TAX_RATE instead of 5.25 r Advantages of using named constants m Easier to understand program because reader can tell how the value is being used m Easier to modify program because value can be changed in one place (the definition) instead of being changed everywhere in the program. m Avoids mistake of changing same value used for a different purpose

24 1/28/03ITM352 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 wait final —the program is not allowed to change the value r The remainder of the definition is similar to a variable declaration and gives the type, name, and initial value. r 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;

25 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 25 Chapter 3 r Branching r Loops r exit(n) method r Boolean data type and expressions Flow of Control

26 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 26 What is “Flow of Control”? r Flow of Control is the execution order of instructions in a program r All programs can be written with three control flow elements: 1. Sequence - just go to the next instruction 2. Selection - a choice of at least two r either go to the next instruction r or jump to some other instruction 3. Repetition - a loop (repeat a block of code) at the end of the loop r either go back and repeat the block of code r or continue with the next instruction after the block r Selection and Repetition are called Branching since these are branch points in the flow of control

27 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 27 Java Flow Control Statements Sequence r the default r Java automatically executes the next instruction unless you use a branching statement Branching: Selection r if r if-else r if-else if-else if- … - else r switch Branching: Repetition r while r do-while r for

28 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 28 Definition of Boolean Values r Branching: there is more than one choice for the next instruction r Which branch is taken depends on a test condition which evaluates to either true or false r In general: if test is true then do this, otherwise it is false, do something else r 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 either true or false  boolean is a primitive data type in Java

29 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 29 Boolean Expressions r Boolean expressions can be thought of as test conditions (questions) that are either true or false r Often two values are compared r For example: Is A greater than B? Is A equal to B? Is A less than or equal to B? etc. r A and B can be any data type (or class), but they should be the same data type (or class)

30 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 30 Java Comparison Operators

31 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 31 Comparing objects r Great care must be taken when comparing objects:  Statements like myRobot == theRobot compare references to where the objects are stored, not the objects themselves! m In general the equals() method is used r The objects themselves define what it means for objects to be equal myRobottheRobot myRobot == theRobot is false aRobot theRobot == aRobot is true

32 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 32 Example: Comparison Methods for String Class r “==“ does not do what you may think for String objects m 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 r are they stored in the same location? r more will be said about this later r Use “.equals” method to test if the strings, themselves, are equal String 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

33 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 33 Compound Boolean Expressions  Use && to AND two or more conditions  Use || to OR two or more conditions r See text for definitions of AND and OR r 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) r In this example the parentheses are not required but are added for clarity m See text (and later slides) for Precedence rules m 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

34 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 34 Java if statement r Simple decisions r Do the next statement if test is true or skip it if false r Syntax: if (Boolean_Expression) Action if true;//execute if true next action;//always executed r Note the indentation for readability (not compile or execution correctness)

35 1/28/03ITM352 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.”);

36 1/28/03ITM352 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) r 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

37 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 37 Two-way Selection: if-else r Select either one of two options r Either do Action1 or Action2, depending on test value r Syntax: if (Boolean_Expression) { Action1 //execute only if true } else { Action2//execute only if false } Action3//always executed

38 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 38 if-else Examples r Example with single-statement blocks: if(time < limit) System.out.println(“You made it.”); else System.out.println(“You missed the deadline.”); r 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; }

39 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 39 Multibranch selection: if-else if-else if-…-else r One way to handle situations with more than two possibilities r Syntax: if(Boolean_Expression_1) Action_1 else if(Boolean_Expression_2) Action_2. else if(Boolean_Expression_n) Action_n else Default_Action

40 1/28/03ITM352 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?)

41 1/28/03ITM352 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”;

42 1/28/03ITM352 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.


Download ppt "ITM352 Conditionals Lecture #5. 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Assignment 1 m Create a Zip file of your JBuilder project."

Similar presentations


Ads by Google