switch-case Statements

Similar documents
Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Arithmetic Compound Assignment Operators

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

++x vs. x++ We will use these notations very often.

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Example: Monte Carlo Simulation 1

Arithmetic Compound Assignment Operators

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Exercise (Revisited)

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Values in 2 s Complement

IEEE Floating-Point Representation 1

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Computer Programming I - Unit 5 Lecture page 1 of 14

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Repetition, Looping. While Loop

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

CompSci 125 Lecture 11

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

REPETITION CONTROL STRUCTURE LOGO

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Problem Solving With Loops

Introduction. C provides two styles of flow control:

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

3 The L oop Control Structure

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

STUDENT LESSON A12 Iterations

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

AP Programming - Chapter 6 Lecture

ECE 122. Engineering Problem Solving with Java

Repetition Structures

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Loops and Expression Types

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Flow Control. CSC215 Lecture

Iteration statements - Loops

Assignment 2.4: Loops

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

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

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

More on control structures

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Introduction to Object-Oriented Programming

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

CS112 Lecture: Repetition Statements

C++ Quick Reference. switch Statements

CS1100 Introduction to Programming

Java Coding 3. Over & over again!

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

Chapter 8. Statement-Level Control Structures

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Chapter 4 Introduction to Control Statements

CS112 Lecture: Loops

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Programming Lecture 4

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

Date: Dr. Essam Halim

Problem Solving and 'C' Programming

Controls Structure for Repetition

Quiz Determine the output of the following program:

Chapter Goals. Contents LOOPS

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

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-Oriented Programming

LECTURE 5 Control Structures Part 2

CIS 3260 Intro to Programming in C#

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

Transcription:

switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break; 12 default: 13 // statements 14 } 15... Zheng-Liang Lu AP Computer Science A: Java Programming 106 / 143

A switch-case statement is more convenient than an if statement for multiple discrete conditions. The variable target, always enclosed in parentheses, must yield a value of char, byte, short, int, or String type. The value v 1,..., and v k must have the same data type as the variable target. In each case, a break statement is a must. 1 break is used to break a construct! The default case, which is optional, can be used to perform actions when none of the specified cases matches target. Counterpart to else statements. 1 If not, there will be a fall-through behavior. Zheng-Liang Lu AP Computer Science A: Java Programming 107 / 143

Example 2 int trafficlight = (int) (Math.random() 3); 3 switch (trafficlight) { 4 case 0: 5 System.out.println("Red"); 6 break; 7 case 1: 8 System.out.println("Yellow"); 9 break; 10 case 2: 11 System.out.println("Green"); 12 break; 13 } 14... Zheng-Liang Lu AP Computer Science A: Java Programming 108 / 143

Conditional Operators A conditional expression evaluates an expression based on the specified condition and returns values accordingly. 2 somevar = booleanexpr? expra : exprb; 3... This is the only ternary operator in Java. If the boolean expression is evaluated true, then return expr A; otherwise, expr B. Zheng-Liang Lu AP Computer Science A: Java Programming 109 / 143

For example, 2 if (num1 > num2) 3 max = num1; 4 else 5 max = num2; 6... Alternatively, one can use a conditional expression like this: 2 max = (num1 > num2)? num1 : num2; 3... Zheng-Liang Lu AP Computer Science A: Java Programming 110 / 143

1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 // keywords: 8 while, do, for, break, continue Zheng-Liang Lu AP Computer Science A: Java Programming 111 / 143

Loops A loop can be used to make a program execute statements repeatedly without having to code the same statements. For example, a program outputs Hello, Java. for 100 times. 2 System.out.println("Hello, Java."); 3 System.out.println("Hello, Java."); 4. 5. // copy and paste for 100 times 6. 7 System.out.println("Hello, Java."); 8... Zheng-Liang Lu AP Computer Science A: Java Programming 112 / 143

2 int cnt = 0; 3 while (cnt < 100) { 4 System.out.println("Hello, Java."); 5 cnt++; 6 } 7... This is a simple example to show the power of loops. In practice, any routine which repeats couples of times 2 can be done by folding them into a loop. 2 I d like to call them patterns. Zheng-Liang Lu AP Computer Science A: Java Programming 113 / 143

成也迴圈, 敗也迴圈 Loops provide significant computational power. Loops bring an efficient way of programming. Loops could consume a lot of time. 3 3 We will visit the analysis of algorithms in the end of this lecture. Zheng-Liang Lu AP Computer Science A: Java Programming 114 / 143

while Loops A while loop executes statements repeatedly while the condition is true. 2 while (condition) { 3 // loop body 4 } 5... The condition should be a Boolean expression which determines whether or not the execution of the body occurs. If true, the loop body is executed and check the condition again. Otherwise, the entire loop terminates. Zheng-Liang Lu AP Computer Science A: Java Programming 115 / 143

Zheng-Liang Lu AP Computer Science A: Java Programming 116 / 143

Example Write a program which sums up all integers from 1 to 100. In math, the question can be written as: sum = 1 + 2 + + 100. But this form is not doable in the machine. 4 4 We need to develop computational thinking. Read http://rsta.royalsocietypublishing.org/content/366/1881/3717.full or http://blog.orangeapple.tw/posts/what-is-computational-thinking/. Zheng-Liang Lu AP Computer Science A: Java Programming 117 / 143

Normally, the machine executes the instructions sequentially. So one needs to decompose the math equation into several steps, like: 2 int sum = 0; 3 sum = sum + 1; 4 sum = sum + 2; 5. 6. 7. 8 sum = sum + 100; 9... It is obvious that many similar statements can be found. Zheng-Liang Lu AP Computer Science A: Java Programming 118 / 143

Using a while loop, the program can be rearranged as follows: 2 int sum = 0; 3 int i = 1; 4 while (i <= 100) { 5 sum = sum + i; 6 ++i; 7 } 8... You should guarantee that the loop will terminate as expected. In practice, the number of loop steps (iterations) is unknown until the input data is given. Zheng-Liang Lu AP Computer Science A: Java Programming 119 / 143

Malfunctioned Loops It is really easy to make an infinite loop. 2 while (true); 3... The common errors of the loops are: never start never stop not complete exceed the expected number of iterations Zheng-Liang Lu AP Computer Science A: Java Programming 120 / 143

Example Write a program which asks the sum of two random integers and lets the user repeatedly enter a new answer until correct. 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random() 10); 4 int y = (int) (Math.random() 10); 5 int ans = x + y; 6 7 System.out.println(x + " + " + y + " =? "); 8 int z = input.nextint(); 9 10 while (z!= ans) { 11 System.out.println("Try again? "); 12 z = input.nextint(); 13 } 14 System.out.println("Correct."); 15 input.close(); 16... Zheng-Liang Lu AP Computer Science A: Java Programming 121 / 143

Loop Design Strategy Writing a correct loop is not an easy task for novice programmers. Consider 3 steps when writing a loop: Find the pattern: identify the statements that need to be repeated. Wrap by loops: put these statements in the loop. Set the continuation condition: translate the criterion from the real world problem into computational conditions. 5 5 Not unique. Zheng-Liang Lu AP Computer Science A: Java Programming 122 / 143

Sentinel-Controlled Loops Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a sentinel value, signifies the end of the loop. For example, the operating systems and the GUI apps. Zheng-Liang Lu AP Computer Science A: Java Programming 123 / 143

Example: Cashier Problem Write a program which sums positive integers from the input except for -1 to exit, and displays the sum. 2 Scanner input = new Scanner(System.in); 3 System.out.println("Enter price ( 1 to exit): "); 4 int curritem = input.nextint(); 5 int sum = 0; 6 while (curritem!= 1) { 7 if (curritem > 0) sum += curritem; 8 System.out.println("Enter price ( 1 to exit): "); 9 curritem = input.nextint(); 10 } 11 System.out.println("Sum = " + sum); 12 input.close(); 13... Line 8 and 9 are the recurrence of Line 3 and 4?! Zheng-Liang Lu AP Computer Science A: Java Programming 124 / 143

do-while Loops A do-while loop is similar to a while loop except that it does execute the loop body first and then checks the loop continuation condition. 2 do { 3 // loop body 4 } while (condition); // Do not miss the semicolon! 5... Note that there is a semicolon at the end of the do-while loop. The do-while loops are also called posttest loops, in contrast to while loops, which are pretest loops. Zheng-Liang Lu AP Computer Science A: Java Programming 125 / 143

Zheng-Liang Lu AP Computer Science A: Java Programming 126 / 143

Example (Revisted) Write a program which sums positive integers from consecutive inputs and displays the sum when the input is 1. 2 Scanner input = new Scanner(System.in); 3 int sum = 0; 4 int curritem; 5 do { 6 System.out.println("Enter price ( 1 to exit): "); 7 curritem = input.nextint(); 8 if (curritem >= 0) sum += curritem; 9 } while (curritem!= 1); 10 System.out.println("Sum = " + sum); 11 input.close(); 12... Zheng-Liang Lu AP Computer Science A: Java Programming 127 / 143

Exercise Write a program which allows the user to enter positive integers consecutively and outputs the maximum when the input is 1. Zheng-Liang Lu AP Computer Science A: Java Programming 128 / 143

2 Scanner input = new Scanner(System.in); 3 int max; 4 5 do { 6 System.out.println("x? ( 1 to exit)"); 7 int x = input.nextint(); 8 if (max < x) { 9 max = x; 10 } 11 } while (x!= 1); 12 13 input.close(); 14... Zheng-Liang Lu AP Computer Science A: Java Programming 129 / 143

for Loops A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates. 2 for (init action; condition; increment) { 3 // loop body 4 } 5... init-action: declare and initialize a variable condition: set a criterion for loop continuation increment: how the variable changes after each iteration Note that these three terms are separated by semicolons. Zheng-Liang Lu AP Computer Science A: Java Programming 130 / 143

Sum from 1 to 100 Example Write a program which sums from 1 to 100. 2 int sum = 0; 3 for (int i = 1; i <= 100; ++i) 4 sum = sum + i; 5... Compared to the while version, 2 int sum = 0; 3 int i = 1; 4 while (i <= 100) { 5 sum = sum + i; 6 ++i; 7 } 8... Zheng-Liang Lu AP Computer Science A: Java Programming 131 / 143

Zheng-Liang Lu AP Computer Science A: Java Programming 132 / 143

Example: Selection Resided in Loop Display all even numbers Write a program which displays all even numbers smaller than 100. An even number is an integer of the form x = 2k, where k is an integer. Zheng-Liang Lu AP Computer Science A: Java Programming 133 / 143

You may use the modular operator (%). 2 for (int i = 1; i <= 100; i++) { 3 if (i % 2 == 0) System.out.println(i); 4 } 5... Also consider this alternative: 2 for (int i = 2; i <= 100; i += 2) { 3 System.out.println(i); 4 } 5... How about odd numbers? Zheng-Liang Lu AP Computer Science A: Java Programming 134 / 143

Example: Monte Carlo Simulation 6 Write a program which conducts a Monte Carlo simulation to estimate π. 6 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu AP Computer Science A: Java Programming 135 / 143

Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue: the loop skips this iteration right after a continue statement is executed. In practice, jump statements in loops should be conditioned. Zheng-Liang Lu AP Computer Science A: Java Programming 136 / 143

Example: Primality Write a program which determines if the input integer is a prime number. Let x > 1 be any natural number. Then x is said to be a prime number if x has no positive divisors other than 1 and itself. It is then straightforward to check if it is prime by dividing x by all natural numbers smaller than x. For speedup, you can divide x by only numbers smaller than x. (Why?) Zheng-Liang Lu AP Computer Science A: Java Programming 137 / 143

2 Scanner input = new Scanner(System.in); 3 System.out.println("Enter x > 2?"); 4 int x = input.nextint(); 5 boolean isprime = true; 6 input.close(); 7 8 for (int y = 2; y < Math.sqrt(x); y++) { 9 if (x % y == 0) { 10 isprime = false; 11 break; 12 } 13 } 14 15 if (isprime) { 16 System.out.println("Prime"); 17 } else { 18 System.out.println("Composite"); 19 } 20... Zheng-Liang Lu AP Computer Science A: Java Programming 138 / 143

Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 2 while (true) { 3 System.out.println("Enter price ( 1 to exit):"); 4 curritem = input.nextint(); 5 if (curritem >= 0) { 6 amount += curritem; 7 } else if (curritem == 1) { 8 System.out.println("Total = " + amount); 9 break; 10 } 11 } 12... Zheng-Liang Lu AP Computer Science A: Java Programming 139 / 143

Another Example Write a program which determines the holding years for an investment doubling its value. Let curr be the current amount, goal be the goal of this investment, and r be the annual interest rate. Then this investment should take at least n years so that the balance of the investment can double its value. Recall that the compounding formula is given by curr = curr (1 + r/100). Zheng-Liang Lu AP Computer Science A: Java Programming 140 / 143

2 int r = 18; // 18% 3 int curr = 100; 4 int goal = 200; 5 6 int years = 0; 7 while (curr <= goal) { 8 curr = (1 + r / 100.0); 9 years++; 10 } 11 12 System.out.println("Years = " + years); 13 System.out.println("Balance = " + curr); 14... Zheng-Liang Lu AP Computer Science A: Java Programming 141 / 143

2 int years = 0; // should be declared here; scope issue 3 for (; curr <= goal; years++) { 4 curr = (1 + r / 100); 5 } 6... 2 int years = 1; // check this initial value 3 for (; true; years++) { 4 curr = (1 + r / 100); 5 if (curr >= goal) break; 6 } 7... A for loop can be an infinite loop by setting true or simply leaving empty in the condition statement. An infinite for loop with an if-break statement is equivalent to a normal while loop. Zheng-Liang Lu AP Computer Science A: Java Programming 142 / 143

Equivalence: while and for Loops (Concluded) In general, a for loop may be used if the number of repetitions is known in advance. If not, a while loop is preferred. Zheng-Liang Lu AP Computer Science A: Java Programming 143 / 143