Selection Statements and operators

Similar documents
Selection Statements and operators

Selection and Repetition Revisited

Selection and Repetition Revisited

Selection and Repetition

Selection and Repetition

Java I/O and Control Structures

Java I/O and Control Structures Algorithms in everyday life

CSC 1051 Data Structures and Algorithms I

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Java Flow of Control

Introduction to Arrays

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Chapter 3. Selections

CSC 1051 Data Structures and Algorithms I

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Algorithms and Conditionals

Using Classes and Objects

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

Iterators and File Input

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CSC 1051 Data Structures and Algorithms I

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

2: Basics of Java Programming

Basics of Java Programming variables, assignment, and input

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

Arrays, Part 3: Multidimensional arrays

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Introduction to Computer Science Unit 2. Exercises

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

File I/O and Exceptions

Lecture 3: Variables and assignment

Where do objects come from? Good question!

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Arrays - Review. Initializer Lists. The for-each Loop. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Conditional Statements

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

1 Short Answer (10 Points Each)

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Control Structures in Java if-else and switch

Conditional Programming

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

Using Classes and Objects

Control Structures in Java if-else and switch

Conditionals and Loops

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Using Classes and Objects

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Designing Classes part 2

BRANCHING if-else statements

Over and Over Again GEEN163

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

COE 211/COE 212 Computer/Engineering Programming. Welcome to Exam II Thursday December 20, 2012

Programming with Java

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Lesson 7 Part 2 Flags

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

COMP 202 Java in one week

CS110 Programming Language I. Lab 6: Multiple branching Mechanisms

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Introduction to Java & Fundamental Data Types

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

COMP 202. Java in one week

Midterm Examination (MTA)

Decisions: Logic Java Programming 2 Lesson 7

Practice Midterm 1 Answer Key

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Java Coding 3. Over & over again!

CMPT 125: Lecture 4 Conditionals and Loops

Top-Down Program Development

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

(c) ((!(a && b)) == (!a!b)) TRUE / FALSE. (f) ((!(a b)) == (!a &&!b)) TRUE / FALSE. (g) (!(!a) && (c-d > 0) && (b!b))

Flow of Control. Chapter 3

CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

Computer Components. Software{ User Programs. Operating System. Hardware

Transcription:

Selection Statements and operators CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus

Selection structures in Java Conditional statement: if (n>0) System.out.println( positive ); else System.out.println( negative ); Other selection structures (Chapter 6 in text) the conditional operator the switch statement

The Conditional Operator Syntax condition? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression

The Conditional Operator Similar to an if-else statement, except that it is an expression that computes a value For example: String result = (happy? "happy" : "sad"); The conditional operator requires three operands so it is sometimes called the ternary operator Hands on: try this in the Person class!

The Conditional Operator Another example: page.drawarc (x+15, y+30, 20, 10, happy?180:0, 180); Hands on: try this in the Smiley class!

The conditional operator is not a statement WRONG!

Quick Check System.out.println ("Your change is " + count + "Dimes")); Rewrite this statement so that "Dime" is printed if count equals 1.

Quick Check Rewrite this code using the conditional operator. if (val <= 10) System.out.println("It is not greater than 10."); else System.out.println("It is greater than 10.");

The switch Statement: multi-way branches Recall: Logic of an if-else statement

The switch Statement: multi-way branches switch statement logic expression evaluated statement1 case: 1 case: 2 statement2 case: 3 statement3 Note: this is a simplified flowchart of the logic of the switch statement

The switch Statement The switch statement provides a way to implement a multi-way choice (not just true/false) The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to the statement associated with the first case value that matches

The switch Statement - example public String tostring() { String result; Hands on: try this in the Die class! switch (facevalue) { case 1: result = "one"; case 2: result = "two"; case 3: result = "three"; return result;

The switch Statement Another example counting letters. Here letter is a char switch (letter) { case 'A': acount++; case 'B': bcount++; case 'C': ccount++;

The switch Statement in general The general syntax of a switch statement is: switch and case are reserved words switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... If expression matches value2, control jumps to here

So the logic of the switch is more like this: expression evaluated 1 2 3 statements1 statements2 statements3 Note: this is a still simplified flowchart of the logic of the switch statement

The switch Statement Optional default case (when no other case matches). The type of a switch expression must be integers, characters, or enumerated types As of Java 7, a switch can also be used with strings You cannot use a switch with floating point values You cannot use ranges of values (eg: 0<x<10) See GradeReport.java

//******************************************************************** // GradeReport.java Author: Lewis/Loftus // // Demonstrates the use of a switch statement. //******************************************************************** import java.util.scanner; public class GradeReport { //----------------------------------------------------------------- // Reads a grade from the user and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) { int grade, category; continue Scanner scan = new Scanner (System.in); System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextint(); category = grade / 10; System.out.print ("That grade is ");

continue switch (category) { case 10: System.out.println ("a perfect score. Well done."); case 9: System.out.println ("well above average. Excellent."); case 8: System.out.println ("above average. Nice job."); case 7: System.out.println ("average."); case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); default: System.out.println ("not passing.");

continue Sample Run switch Enter (category) a numeric grade (0 to 100): 91 { That grade is well above average. Excellent. case 10: System.out.println ("a perfect score. Well done."); case 9: System.out.println ("well above average. Excellent."); case 8: System.out.println ("above average. Nice job."); case 7: System.out.println ("average."); case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); default: System.out.println ("not passing.");

continue switch (category) { case 10: System.out.println ("a perfect score. Well done."); case 9: System.out.println ("well above average. Excellent."); case 8: System.out.println ("above average. Nice job."); case 7: System.out.println ("average."); case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); default: System.out.println ("not passing."); Hands on: try removing this break statement

Another example SwitchExample.java //*********************************************************************** // SwitchExample.java Author: M A Papalaskari // Example of switch statement that does NOT use break after each case. //*********************************************************************** import java.util.scanner; public class SwitchExample { // Example of using a switch statement. Counts number of digits, zeros, // whitespace, and others in a line of input. " public static void main (String[] args) " { Scanner scan = new Scanner(System.in); int digits = 0, zeros = 0, whitespace = 0, other = 0; System.out.print("Input line>"); String message = scan.nextline(); int count = 0; continue

while (count < message.length()) { switch (message.charat(count)) { case '0': zeros++; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': digits++; " case ' ': case '\t : whitespace++; default: other++; // end switch count++; // end while System.out.print(digits + " Digit" + (digits==1? "" : "s")); System.out.print(", of which " + zeros); System.out.println((zeros==1? " is a zero " : " are zeros ")); System.out.println(whitespace + " whitespace"); System.out.println(other + " other" + (other==1? "" : "s"));

while (count < message.length()) { switch (message.charat(count)) { case '0': zeros++; case '1': case '2': Sample Run¼¼ case '3': case '4': Input line>10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Lift off! case '5': ÏÏ 11 Digits, of which 1 is a zero case '6': ÏÏ Ï11 whitespace case '7': ÏÏ Ï18 others case '8': case '9': digits++; " case ' ': case '\t : whitespace++; default: other++; // end switch count++; // end while System.out.print(digits + " Digit" + (digits==1? "" : "s")); System.out.print(", of which " + zeros); System.out.println((zeros==1? " is a zero " : " are zeros ")); System.out.println(whitespace + " whitespace"); System.out.println(other + " other" + (other==1? "" : "s"));

Homework Review Sections 6.1 and 6.2 Always do all self-review exercises when you review Exercises be sure to do all the hands-on exercises in this presentation. Try also the following: Implement the Dog class, similar to the Person class. In addition to being happy or sad, the dog should also have another state symbolized by an integer: 1=sit; 2=sleep; 3=shake; 4=run. Use a switch statement in tostring() method to indicate the state of the dog Incorporate the conditional operator and the switch statement in your next project.