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.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

CS0007: Introduction to Computer Programming
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.
Primitive Types and Simple I/O
Branching Loops exit(n) method Boolean data type and expressions
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
ITM 352 Types, Strings, Simple I/O Lecture #4. 1/16/03ITM Spring, © PortIntro to OOP - 2 Announcements r Assignments m Hints to Assignment.
Primitive Types, Strings, and Console I/O
ITM352 Loops Lecture #6. 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Lab class dates have changed!!! m Check the “Weekly Schedule”
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Basic Elements of C++ Chapter 2.
Chapter 2 Primitive Data types Strings: a class Assignment Expressions Keyboard and Screen I/O Documentation & Style Primitive Types and Simple I/O.
Lecturer: Dr. AJ Bieszczad Chapter 2 COMP 150: Introduction to Object-Oriented Programming 2-1 l Primitive Data types l Strings: a class l Assignment l.
Chapter 2Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 2 l Primitive Data types l Strings: a class l Assignment l.
Chapter 2Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 2 l Primitive Data types l Strings: a class l Assignment l.
Chapter 2Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 2 l Primitive Data types l Strings: a class l Assignment l.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
ITM 352 Flow-Control: if and switch. ITM © Port, KazmanFlow-Control - 2 What is "Flow of Control"? Flow of Control is the execution order of instructions.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
ITM © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings.
Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
Flow of Control Chapter 3 Flow of control Branching Loops
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 2Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 2 l Primitive Data types l Strings: a class l Assignment l.
Introduction to Java Java Translation Program Structure
Chapter 2Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Reminders/Info l Project 1 available (due Thursday 01/27, 10:30 pm)
Chapter 3 1 l Branching l Loops l exit(n) method l Boolean data type and logic expressions Flow of Control – Part 1.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Announcements Quiz 1 Next Monday. int : Integer Range of Typically –2,147,483,648 to 2,147,483,647 (machine and compiler dependent) float : Real Number.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
COMP 110: Spring Announcements Lab 1 due Wednesday at Noon Assignment 1 available on website Online drop date is today.
Computer Programming with Java Chapter 2 Primitive Types, Assignment, and Expressions.
Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-1 l Branching l Loops l exit(n) method l Boolean data type.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Java-02 Basic Concepts Review concepts and examine how java handles them.
ITM © Port, KazmanVariables - 1 ITM 352 Data types, Variables Class #4.
Chapter 2Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 2 l Primitive Data types l Strings: a class l Assignment l.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
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.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Chapter Topics The Basics of a C++ Program Data Types
Data Types and Expressions
Data Types and Expressions
Lecture 3: Operators, Expressions and Type Conversion
Introduction to Computer Science / Procedural – 67130
Basic Elements of C++.
ITM 352 Flow-Control: if and switch
ITM 352 Expressions, Precedence, Working with Strings Class #5
Branching Loops exit(n) method Boolean data type and expressions
Basic Elements of C++ Chapter 2.
IDENTIFIERS CSC 111.
Chapter 2 Edited by JJ Shepherd
CMSC 202 Java Primer 2.
Expressions and Assignment
elementary programming
Web Programming– UFCFB Lecture 20
Primitive Types, Strings, and Console I/O
Primitive Types and Expressions
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

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 directory (the folder that contains the.jpr or.jpx file, your source code, etc.) and it as an attachment to m If you don’t know how to create a Zip file or 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!!!

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)

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

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

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

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

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 r e (or scientific, or floating- point) notation, e.g e2, which means 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:

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)

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

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

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 = ; 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

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

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

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”

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 for more details!

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 >

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

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

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 ( …) (see text for more examples)

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

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.

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

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 = ;

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

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

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

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

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)

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

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

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

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

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)

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.”);

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

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

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; }

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

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

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”;

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.