1 Chapter 4 - Control Statements Conditions if Statement && Logical Operator || Logical Operator ! Logical Operator switch Statement while Loop do Loop.

Slides:



Advertisements
Similar presentations
Chapter 4 - Control Statements
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.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 2 - Algorithms and Design
Java Programming: From the Ground Up
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Chapter 5: Control Structures II
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Advanced Programming Java
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Lecture 4b Repeating With Loops
Java Programming Fifth Edition
REPETITION CONTROL STRUCTURE
Loops.
Chapter 5: Control Structures II
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Repetition-Counter control Loop
Lecture 07 More Repetition Richard Gesick.
Control Statement Examples
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Java Programming Control Structures Part 1
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Lecture Notes – Week 2 Lecture-2
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

1 Chapter 4 - Control Statements Conditions if Statement && Logical Operator || Logical Operator ! Logical Operator switch Statement while Loop do Loop for Loop Loop Comparison Nested Loops Boolean Variables Input Validation Boolean Logic Expression Evaluation Practice 1

2 Conditions Throughout this chapter, you’ll see if statements and loop statements where conditions appear within a pair of parentheses, like this: if ( ) {... } while ( ) {... } Typically, each condition involves some type of comparison and the comparisons use comparison operators…. 1

3 Conditions Here are Java's comparison operators: ==, !=,, = Each comparison operator evaluates to either true or false. == Tests two operands for equality. 3 == 3 evaluates to true 3 == 4 evaluates to false Note that == uses two equal signs, not one! != Tests two operands for inequality. The != operator is pronounced “not equal.” The, = operators work as expected. 1

4 if Statement Use an if statement if you need to ask a question in order to determine what to do next. There are three forms for an if statement: if by itself Use for problems where you want to do something or nothing. if, else Use for problems where you want to do one thing or another thing. if, else if Use for problems where you want to do one thing out of three or more choices. 1

5 if Statement pseudocode syntax if by itself: if if, else : if else Java syntax if by itself: if ( ) { } if, else : if ( ) { } else { }

6 if Statement pseudocode syntax if, else if : if else if. else Java syntax if, else if, else : if ( ) { } else if ( ) { }. else { } more else if's here (optional) optional more else if's here (optional) optional 1 2 3

7 if Statement Write a complete program that prompts the user to enter a sentence and then prints an error message if the last character is not a period. sample session: Enter a sentence: Permanent good can never be the outcome of violence Invalid entry – your sentence needs a period! Italics indicates input. Never hardcode (include) input as part of your source code!!!

8 if Statement (hidden) Pseudocode: print "Enter a sentence: " input sentence if sentence's last character ≠ '.' print "Invalid entry - your sentence needs a period!" 1

9 if Statement (hidden) Java program: import java.util.Scanner; public class SentenceTester { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); String sentence; int lastCharPosition; System.out.println("Enter a sentence:"); sentence = stdIn.nextLine(); lastCharPosition = sentence.length() - 1; if (sentence.charAt(lastCharPosition) != '.') { System.out.println( "Invalid entry - your sentence needs a period!"); } } // end main } // end class SentenceTester 1 2 3

10 && Logical Operator Suppose you want to print "OK" if the temperature is between 50 and 90 degrees and print "not OK" otherwise. Here's the pseudocode solution: if temp  50 and  90 print "OK" else print "not OK" 1

11 && Logical Operator And here's the solution using Java: if (temp >= 50 && temp <= 90) { System.out.println("OK"); } else { System.out.println("not OK"); } In Java, if two criteria are required for a condition to be satisfied (e.g., temp >= 50 and temp <= 90), then separate the two criteria with the && (and) operator. If both criteria use the same variable (e.g., temp ), you must include the variable on both sides of the &&

12 && Logical Operator The program on the next slide determines whether fans at a basketball game win free french fries. If the home team wins and scores at least 100 points, then the program prints this message: Fans: Redeem your ticket stub for a free order of french fries at Yummy Burgers. On the next slide, replace with appropriate code.

13 && Logical Operator /*************************************** * FreeFries.java * Dean & Dean * * This program reads points scored by the home team * and the opposing team and determines whether the * fans win free french fries. ***************************************/ import java.util.Scanner; public class FreeFries { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int homePts; // points scored by home team int opponentPts; // points scored by opponents System.out.print("Home team points scored: "); homePts = stdIn.nextInt(); System.out.print("Opposing team points scored: "); opponentPts = stdIn.nextInt(); } // end main } // end class FreeFries 1 2

14 || Logical Operator Provide code that prints "bye" if a response variable contains a lowercase or uppercase q (for quit). Here’s a pseudocode implementation: if response equals “q” or “Q” print “Bye” To implement “or” logic in Java, use || (the or operator). Here’s the Java implementation: if (response.equals(″q″) || response.equals(″Q″)) { System.out.println("bye"); } 1 When using the || operator, if both criteria in the or condition use the same variable (e.g., response ), you must include the variable on both sides of the ||. 2 3

15 || Logical Operator It’s a common bug to forget to repeat a variable that’s part of an || (or &&) condition. This code generates a compilation error: if (response.equals(″q″ || ″Q″)) { System.out.println("bye"); } Another common bug is to use the == operator to compare strings for equality. This code compiles successfully, but it doesn’t work properly: if (response == ″q″ || response == ″Q″) { System.out.println("bye"); } 1 2

16 || Logical Operator As an alternative to using the || operator with two equals method calls, you could use an equalsIgnoreCase method call like this: if (response.equalsIgnoreCase("q")) { System.out.println("Bye"); }

17 ! Logical Operator The ! (not) operator reverses the truth or falsity of a condition. To print "Let's get started...." if a response variable does not contain a lowercase or uppercase q, do this: if (!(response == 'q' || response == 'Q')) { System.out.println("Let's get started....");

18 switch Statement When to use a switch statement: If you need to do one thing from a list of multiple possibilities. Note that the switch statement can always be replaced by an if, else if, else statement, but the switch statement is considered to be more elegant. Syntax: switch ( ) { case : ; break; case : ; break;... default: ; } // end switch

19 switch Statement How the switch statement works: Jump to the case constant that matches the controlling expression's value (or jump to the default label if there are no matches) and execute all subsequent statements until reaching a break. The break statement causes a jump out of the switch statement (below the "}"). Usually, break statements are placed at the end of every case block. However, that's not a requirement and they're sometimes omitted for good reasons. Put a : after each case constant. Even though statements following the case constants are indented, { }'s are not necessary. The controlling expression should evaluate to either an int or a char. Proper style dictates including "// end switch" after the switch statement's closing brace

20 switch Statement Given this code fragment: i = stdIn.nextInt(); switch (i) { case 1: System.out.print("A"); break; case 2: System.out.print("B"); case 3: case 4: System.out.print("C-D"); break; default: System.out.print("E-Z"); } // end switch If input = 1, what's the output? If input = 2, what's the output? If input = 3, what's the output? If input = 4, what's the output? If input = 5, what's the output?

21 switch Statement Write a program that reads in a ZIP Code and uses the first digit to print the associated geographic area: if zip codeprint this begins withmessage 0, 2, 3 is on the East Coast. 4-6 is in the Central Plains area. 7 is in the South. 8-9 is in the West. other is an invalid ZIP Code. Note: represents the entered ZIP Code value. 1

22 switch Statement (hidden) import java.util.Scanner; public class ZipCode { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); String zip; // user-entered zip code System.out.print("Enter a ZIP Code: "); zip = stdIn.nextLine(); switch (zip.charAt(0)) { case '0': case '2': case '3': System.out.println(zip + " is on the East Coast."); break; case '4': case '5': case '6': System.out.println(zip + " is in the Central Plains area."); break; case '7': System.out.println(zip + " is in the South."); break; case '8': case '9': System.out.println(zip + " is in the West."); break; default: System.out.println(zip + " is an invalid ZIP Code."); } // end switch } // end main } // end class ZipCode 1 2

23 while Loop pseudocode syntax while Java syntax while ( ) { } Use a loop statement if you need to do the same thing repeatedly

24 while Loop Write a main method that finds the sum of user- entered integers where is a sentinel value. public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int sum = 0; // sum of user-entered values int x; // a user-entered value System.out.print("Enter an integer ( to quit): "); x = stdIn.nextInt(); while (x != ) { sum = sum + x; System.out.print("Enter an integer ( to quit): "); x = stdIn.nextInt(); } System.out.println("The sum is " + sum); } // end main

25 do Loop When to use a do loop: If you know that the repeated thing will always have to be done at least one time. Syntax: do { } while ( ); Note: The condition is at the bottom of the loop (in contrast to the while loop, where the condition is at the top of the loop). The compiler requires putting a ";" after the ")". Proper style dictates putting the "while" part on the same line as the "}" 1 2 3

26 do Loop do loop example: As part of an architectural design program, write a main method that prompts the user to enter length and width dimensions for each room in a proposed house so that total floor space can be calculated for the entire house. After each length/width entry, ask the user if there are any more rooms. Print the total floor space. 1 2

27 do Loop (hidden) public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); double length, width; // room dimensions double totalFloorSpace = 0; // house's total floor space String response; // user's y/n response do { System.out.print("Enter the length: "); length = stdIn.nextDouble(); System.out.print("Enter the width: "); width = stdIn.nextDouble(); totalFloorSpace += length * width; System.out.print("Any more rooms? (y/n): "); response = stdIn.next(); } while (response.equalsIgnoreCase("y")); System.out.println("The total floor space is " + floorSpace); } // end main 1

28 for Loop When to use a for loop: If you know the exact number of loop iterations before the loop begins. For example, use a for loop to: Print this countdown from 10. Sample session: Liftoff! Find the factorial of a user-entered number. Sample session: Enter a whole number: 4 4! =

29 for Loop for loop syntax for ( ; ; ) { } for loop example for (int i=10; i>0; i--) { System.out.print(i + " "); } System.out.println(“Liftoff!”); for loop semantics: Before the start of the first loop iteration, execute the initialization component. At the top of each loop iteration, evaluate the condition component: If the condition is true, execute the body of the loop. If the condition is false, terminate the loop (jump to the statement below the loop's closing brace). At the bottom of each loop iteration, execute the update component and then jump to the top of the loop

30 for Loop Trace this code fragment with an input value of 3. Scanner stdIn = new Scanner(System.in); int number; // user entered number double factorial = 1.0; // factorial of user entry System.out.print("Enter a whole number: "); number = stdIn.nextInt(); for (int i=2; i<=number; i++) { factorial *= i; } System.out.println(number + "! = " + factorial); for loop index variables are often, but not always, named i for “index.” Declare for loop index variables within the for loop heading. 5 6

31 for Loop Write a main method that prints the squares for each odd number between 1 and 99. Sample session:

32 Loop Comparison for loop: do loop: while loop: When to use If you know, prior to the start of loop, how many times you want to repeat the loop. If you always need to do the repeated thing at least one time. If you can't use a for loop or a do loop. Template for (int i=0; i<max; i++) { } do { } while ( ); while ( ) { }

33 Loop Comparison (hidden) for loop: do loop: while loop: When to use If you know, prior to the start of loop, how many times you want to repeat the loop. If you always need to do the repeated thing at least one time. If you can't use a for loop or a do loop. Template for (int i=0; i<max; i++) { } do { } while ( ); while ( ) { }

34 Nested Loops Nested loops = a loop within a loop. Example – Write a program that prints a rectangle of characters where the user specifies the rectangle's height, the rectangle's width, and the character's value. Sample session: Enter height: 4 Enter width: 3 Enter character: < <<<

35 Nested Loops (hidden) import java.util.Scanner; public class Rectangle { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int height, width; // rectangle's dimensions char printCharacter; System.out.print("Enter height: "); height = stdIn.nextInt(); System.out.print("Enter width: "); width = stdIn.nextInt(); System.out.print("Enter character: "); printCharacter = stdIn.next().charAt(0); for (int row=1; row<=height; row++) { for (int col=1; col<=width; col++) { System.out.print(printCharacter); } System.out.println(); } } // end main } // end class Rectangle

36 Nested Loops (hidden) import java.util.Scanner; public class Rectangle { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int height, width; // rectangle's dimensions char printCharacter; int row, col; System.out.print("Enter height: "); height = stdIn.nextInt(); System.out.print("Enter width: "); width = stdIn.nextInt(); System.out.print("Enter character: "); printCharacter = stdIn.next().charAt(0); for (row=1; row<=height; row++) { for (col=1; col<=width; col++) { System.out.print(printCharacter); } System.out.println(); } } // end main } // end class Rectangle

37 Nested Loops (hidden) import java.util.Scanner; public class Rectangle { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int height, width; // rectangle's dimensions char printCharacter; int row, col; System.out.print("Enter height: "); height = stdIn.nextInt(); System.out.print("Enter width: "); width = stdIn.nextInt(); System.out.print("Enter character: "); printCharacter = stdIn.next().charAt(0); for (row=1; row<=height; row++) { for (col=1; col<=width; col++) { System.out.print(printCharacter); } System.out.println(); } } // end main } // end class Rectangle

38 Boolean Variables Programs often need to keep track of the state of some condition. For example, if you're writing a program that simulates the operations of a garage door opener, you'll need to keep track of the state of the garage door's direction - is the direction up or down? You need to keep track of the direction "state" because the direction determines what happens when the garage door opener's button is pressed. If the direction state is up, then pressing the garage door button causes the direction to switch to down. If the direction state is down, then pressing the garage door button causes the direction to switch to up. To implement the state of some condition, use a boolean variable. 1

39 Boolean Variables A boolean variable is a variable that: Is declared to be of type boolean. Holds the value true or the value false. Boolean variables are good at keeping track of the state of some condition when the state has one of two values. For example: Values for the state of a garage door opener's direction Associated values for a boolean variable named upDirection uptrue downfalse

40 Boolean Variables This code fragment initializes an upDirection variable to true and shows how to toggle its value within a loop. boolean upDirection = true; do {... upDirection = !upDirection;... } while ( ); If upDirection holds the value true, this statement changes it to false, and vice versa. 2 1

41 Boolean Variables 1 import java.util.Scanner; public class GarageDoor { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); String entry; // user's entry - enter key or q boolean upDirection = true; // Is the current direction up? boolean inMotion = false; // Is garage door currently moving? System.out.println("GARAGE DOOR OPENER SIMULATOR\n"); do { System.out.print("Press Enter, or enter 'q' to quit: "); entry = stdIn.nextLine(); if (entry.equals("")) // pressing Enter generates "" { inMotion = !inMotion; // button toggles run state

42 Boolean Variables 1 if (inMotion) { if (upDirection) { System.out.println("moving up"); } else { System.out.println("moving down"); } else { System.out.println("stopped"); upDirection = !upDirection; // direction reverses at stop } } // end if entry = "" } while (entry.equals("")); } // end main } // end GarageDoor class

43 Input Validation boolean variables are often used for input validation. Input validation is when a program checks a user's input to make sure it's valid, i.e., correct and reasonable. If it's valid, the program continues. If it's invalid, the program enters a loop that warns the user about the erroneous input and then prompts the user to re-enter. In the GarageDoor program, note how the program checks for an empty string (which indicates the user wants to continue), but it doesn't check for a q. 1

44 Input Validation To add input validation to the GarageDoor program, replace the GarageDoor program's prompt with the following code. It forces the user to press Enter or enter a q or Q. validEntry = false; do { System.out.print("Press Enter, or enter 'q' to quit: "); entry = stdIn.nextLine(); if (entry.equals("") || entry.equalsIgnoreCase("q")) { validEntry = true; } else { System.out.println("Invalid entry."); } } while (validEntry == false); 1 What is a more elegant implementation for this? 2 3 4

45 Boolean Logic Boolean logic (= Boolean algebra) is the formal logic that determines how conditions are evaluated. The building blocks for Boolean logic are things that you've already seen - the logical operators &&, ||, and !. Logical operator review: For the && operator, both sides need to be true for the whole thing to be true. For the || operator, only one side needs to be true for the whole thing to be true. The ! operator reverses the truth or falsity of something. 1 2

46 Expression Evaluation Practice Assume: boolean ok = false; double x = 6.5, y = 10.0; Evaluate these expressions: (x != 6.5) || !ok true && 12.0 < x + y 1 2 3

47 Chapter 4 – Quiz Questions 2.What Java statement provides multiple branching functionality? a)option b)shuttle c)switch 3.What Java loop statement has three components in its heading? a)repeat loop statement b)for loop statement c)again loop statement 1.What Java operator reverses the truth or falsity of a condition? a)& b)% c)!