Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.

Slides:



Advertisements
Similar presentations
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Arrays, Conditionals & Loops in Java. Arrays in Java Arrays in Java, are a way to store collections of items into a single unit. The array has some number.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
UNIT II Decision Making And Branching Decision Making And Looping
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.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Java Unit 9: Arrays Declaring and Processing Arrays.
IE 212: Computational Methods for Industrial Engineering
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
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.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Control Structures By Shyam Gurram. Control Structure In this chapter we have two different types of structures. Conditional Structure Iterative Control.
Controlling Execution Dong Shao, Nanjing Unviersity.
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.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
JavaScript, Fourth Edition
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Matlab tutorial course Lesson 4: Writing your own functions: programming constructs
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
Application development with Java Lecture 6 Rina Zviel-Girshin.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 8 Java Fundamentals Control Structures Fri.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 How did your team meetings go? A list of three possible “adoptable” projects is linked near the bottom.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Spring 2006CISC101 - Prof. McLeod1 Last Time Built “HelloWorld.java” in BlueJ (and Eclipse). Looked at Java keywords. Primitive types. Expressions: Variables,
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Today… Operators, Cont. Operator Precedence Conditional Statement Syntax. Winter 2016CISC101 - Prof. McLeod1.
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
Last Time Unary operators: Other Assignment operators
EGR 2261 Unit 4 Control Structures I: Selection
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
JavaScript: Control Statements.
Arrays, For loop While loop Do while loop
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
In this class, we will cover:
CSC215 Lecture Control Flow.
CISC124 Labs start this week in JEFF 155.
CISC124 Labs start this week in JEFF 155. Fall 2018
CMPE212 – Reminders The other four assignments are now posted.
CISC101 Reminders All assignments are now posted.
CMPE212 – Reminders The other four assignments are now posted.
In this class, we will cover:
CISC101 Reminders Assignment 3 due today.
CSC215 Lecture Control Flow.
Presentation transcript:

Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1

Method Invocations – 1. Naming the Method If the method is in the same class, then just use the name of the method. –(The compiler assumes the existence of the object reference to the current object as this. or it assumes the name of the current object, when static) If the method is not in the same class you must first identify the object owning the method and obtain the method using the dot operator. If the method is declared as static, then you can invoke the method without instantiating the class that contains the method. Winter 2016CMPE212 - Prof. McLeod2

Method Invocations – 2. Providing Arguments for the Parameters If the method has been declared to accept arguments, ie. it has a non-empty parameter list, then you must supply a matching list of arguments. If the method does not have any parameters, then you must still use empty brackets, ( ), when you invoke the method. Winter 2016CMPE212 - Prof. McLeod3

Method Invocations – 3. Using a Return Value A non- void method will return something. You can use that “something” in an expression, or just store it in a variable – your choice. The method has declared the type of that “something”. If the method was declared as void, you will not get a return value and you can only invoke the method by itself, not as part of an expression or an assignment statement. Winter 2016CMPE212 - Prof. McLeod4

Winter 2016CMPE212 - Prof. McLeod5 We will consider if, if-else and switch statements. Simple if statement syntax : if (boolean_expression) statement_when_true; Example: if (capacitance < 0) System.out.println(“Illegal capacitance”); Conditionals or “Selection Statements”

Winter 2016CMPE212 - Prof. McLeod6 if-else Statement Syntax of if-else statement: if (boolean_expression) statement_when_true; else statement_when_false; Example: if (stress > maxStress / 1.5) result = “failure”; else result = “pass”;

Winter 2016CMPE212 - Prof. McLeod7 if-else Statement, Cont. With statement blocks: if (boolean_expression) { block_of_code_when_true } else { block_of_code_when_false } Note indentation and bracket alignment.

Abbreviated if Statement Uses the “ternary operator” - ? expression1 ? expression2 : expression3 expression1 must evaluate to a boolean expression2 (when true) and expression3 (when false) must evaluate to the same type. You could use this with an assignment, for example: int smaller = a <= b ? a : b; stores the smaller of the two numbers in smaller. Winter 2016CMPE212 - Prof. McLeod8

Winter 2016CMPE212 - Prof. McLeod9 “Chained” if Statements Syntax: if (condition1) { block1 } else if (condition2) { block2 } else if (condition3) { block3 } else if (condition4) { block4 } … else { blockn } Each condition is tested in turn, until one is evaluated to true. If none of them are true then the else block is executed.

Dangling else Problem It is not unusual to nest if statements inside each other. One issue that can arise is the “Dangling else” problem. Indentation might give a visual clue, but has no syntactic meaning. The else should be associated with the closest if. Use { } if necessary. Winter 2016CMPE212 - Prof. McLeod10

Winter 2016CMPE212 - Prof. McLeod11 switch Statement Syntax: switch (expression) { case val1: // statements if expression produces val1 break; case val2: // statements if expression produces val2 break; case val3: … default: // statements if none of the above is true } // end switch

Winter 2016CMPE212 - Prof. McLeod12 switch Statement - Cont. The code to be run depends on which val# value matches expression. If none match, the statements after the default: clause are run. The expression and val# values (or “Case Labels”) must all be of the same integer (or char) type or of type String. The break; statements make sure that following cases are not executed after a match has been made. It is possible to do multiple cases on one line, but it is clumsy:

Winter 2016CMPE212 - Prof. McLeod13 switch Statement - Cont. switch (expression) { case val1: case val2: case val3: // statements if expression is val1, val2 or val3 break; case val4: case val5: // statements if expression is val4 or val5 break; case val6: … default: // statements if none of the above is true break; } // end switch

Winter 2016CMPE212 - Prof. McLeod14 switch Statement - Cont. Menu coding is a possible use: –Provide a number of options to the user, like “(A)dd, (E)dit or (D)elete”. –The user presses a, e, d, A, E, D, or some other key. –In a switch statement, you would have:

Winter 2016CMPE212 - Prof. McLeod15 switch Statement - Cont. switch (userResponse) { // userResponse is a char case ‘a’: case ‘A’: // Add operation code break; case ‘e’: case ‘E’: // Edit operation code break; case ‘d’: case ‘D’: // Delete operation code break; default: // Tell user wrong key pressed } // end switch

switch Statement Example See Java7Switch.java. Comparisons are case sensitive when using Strings. As if.equals() is being used. Generates more efficient bytecode than what you would get from a chained if construct. Winter 2016CMPE212 - Prof. McLeod16

CMPE212 - Prof. McLeod17 Repetition or Using “Loops” Java has: –while –do/while –for –The “for each” loop Also will discuss the use of break and continue Winter 2016

CMPE212 - Prof. McLeod18 while loop syntax: while ( boolean_expression ) { block_of_code } As long as boolean_expression evaluates to true the statements in the block_of_code continue to execute. One statement inside the loop does not need { }. By mistake, you might write the following - what would happen? while ( boolean_expression ); line_of_code “ while ” loop - Cont. Winter 2016

CMPE212 - Prof. McLeod19 Syntax: do { block_of_code } while ( boolean_expression ); Note the “ ; ” at the end of the while statement. Since the conditional test is at the end of the loop, it will always execute the loop at least once. “ do / while ” loop Winter 2016

CMPE212 - Prof. McLeod20 “ for ” loop The kind of while loop shown below: int i = 1; while (i < 21) { // other statements i = i + 1; } is used so often, that Java has provided another looping structure that does all that is shown above, but needs only one line: for (int i = 1; i < 21; i = i + 1) { // other statements } or i++ Winter 2016

CMPE212 - Prof. McLeod21 Syntax: for (initialization; boolean_expression; update) { block_of_code } for loops are used when you know, in advance, the number of repetitions desired. If there is only one statement inside the loop you don’t need the { } brackets. “ for ” loop - Cont. Winter 2016

CMPE212 - Prof. McLeod22 “ for ” loop - Cont. You don’t have to declare the counter inside the for loop, if you have declared it earlier in your program. But if you do declare it in the for statement then the scope of that variable will only be inside the loop block. Winter 2016

Often, you will want to visit every element in a collection, not just a part. Syntax of the “for each” loop: for (type variable : collection) { // statements } CMPE212 - Prof. McLeod23 “for each” Loop Winter 2016

CMPE212 - Prof. McLeod24 “for each” Loop, Cont. For example, suppose we have an array called data, containing a collection of double type numbers, and you want to add them all up: double sum = 0; for (double e : data) sum = sum + e; or sum += e; Winter 2016

CMPE212 - Prof. McLeod25 “for each” Loop, Cont. Equivalent normal for loop: double sum = 0; for (int i = 0; i < data.length; i++) sum = sum + data[i]; The “for each” loop is a bit easier with arrays, but is even better suited for other kinds of collections. Winter 2016

CMPE212 - Prof. McLeod26 Loops - Misc. Don’t declare variables inside loops, as the repeated declaration process uses up time and memory unnecessarily. There is no limit in Java to how many levels you can nest loops. It is customary, but not necessary, to use the variables i, j, k as loop counters, when the counter has no intrinsic meaning. Winter 2016

CMPE212 - Prof. McLeod27 Other Java Keywords Used With Loops break and continue The continue statement interrupts the execution of a loop, and returns control to the top of the loop. The break statement interrupts the execution of a loop, and transfers control to the first statement after the loop. Winter 2016

Use of continue For example: for (i = 1; i <= 5; i++) { if ( i == 3 ) continue; System.out.println(“i = ” + i); } System.out.println(“End of Loop!”); Displays: CMPE212 - Prof. McLeod28 i = 1 i = 2 i = 4 i = 5 End of Loop! Winter 2016

Use of break For example: for (i = 1; i <= 5; i++) { if ( i == 3 ) break; System.out.println(“i = ” + i); } System.out.println(“End of Loop!”); Displays: CMPE212 - Prof. McLeod29 i = 1 i = 2 End of Loop! Winter 2016

CMPE212 - Prof. McLeod30 Use of “ break ” & “ continue ” Only use these keywords when it makes your code easier to read. Avoid the use of more than one break or continue inside a loop. If you use a simple condition to issue a break statement, then why can’t you put that condition in the loop test? Overuse of break statements can lead to “spaghetti” code - just like the use of “goto” statements! Winter 2016

Introduction to Multi-Dimensional Arrays We have discussed the declaration of 1D arrays. For example: double[] oneD = new double[100]; To assign values, for example: for (int i = 0; i < oneD.length; i++) oneD[i] = i; Winter 2016CMPE212 - Prof. McLeod31

Multi-Dimensional Arrays, Cont. For each dimension, just add another set of [ ] : int[][] twoD = new int[4][20]; Has room for 80 values. To assign, for example: int row, col; for (row = 0; row < twoD.length; row++) for (col = 0; col < twoD[row].length; col++) twoD[row][col] = row * col; Winter 2016CMPE212 - Prof. McLeod32

Multi-Dimensional Arrays, Cont. It is helpful to think of a 2D array as storing tabular data, like a spreadsheet. For convenience (and to help you code consistently) you can think of the first dimension as the rows and the second dimension as the columns. To get the number of rows, use twoD.length, and to get the number of columns, grab one of the rows and use twoD[0].length. Winter 2016CMPE212 - Prof. McLeod33

Multi-Dimensional Arrays, Cont. You can use three sets of [ ] to get a 3 dimensional array. Using the spreadsheet analogy, the third dimension could be the sheet number, where each sheet contains a table. For a good analogy for a 4D array you might need to look up a Star Trek script… For assignment 1, you will need 1D and 2D arrays. Methods can return arrays and can accept them as parameters. Winter 2016CMPE212 - Prof. McLeod34

Iterating 2D Arrays See TestLoops.java Can a for/each loop be used to assign or alter values in an array? Winter 2016CMPE212 - Prof. McLeod35