Lesson 4B Conditionals switch case. By John B. Owen All rights reserved 2011, revised 2014

Similar documents
Lesson 7A Arrays. By John B. Owen All rights reserved 2011, revised 2014

Lesson 1A - First Java Program HELLO WORLD With DEBUGGING examples. By John B. Owen All rights reserved 2011, revised 2015

Switch Statement (Outsource: )

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

Lesson 8 Passing Parameters. By John B. Owen All rights reserved 2011, revised 2014

Lesson 7B Array methods. By John B. Owen All rights reserved 2011, revised 2014

Lesson 6E Nested Loops. By John B. Owen All rights reserved 2011, revised 2014

Lesson 5C MyClass Methods. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Lesson 2A Data. Data Types, Variables, Constants, Naming Rules, Limits. A Lesson in Java Programming

Introduction to Programming

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Unit: Rational Number Lesson 3.1: What is a Rational Number? Objectives: Students will compare and order rational numbers.

Subtracting with Multi-Digit Numbers Adaptable for 2 nd, 3 rd, 4 th, and 5 th grades*

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

Memory Addressing, Binary, and Hexadecimal Review

Variables and Constants

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Topic C. Communicating the Precision of Measured Numbers

Number Systems MA1S1. Tristan McLoughlin. November 27, 2013

3D Graphics Programming Mira Costa High School - Class Syllabus,

Qualifying Exam Languages

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

When using computers, it should have a minimum number of easily identifiable states.

BRANCHING if-else statements

Excerpt from: Stephen H. Unger, The Essence of Logic Circuits, Second Ed., Wiley, 1997

T02 Tutorial Slides for Week 2

Decision Making in C

Computing and compilers

SKILL AREA 304: Review Programming Language Concept. Computer Programming (YPG)

NUMERIC SYSTEMS USED IN NETWORKING

Binary Systems and Codes

Lecture 1: Overview

SCRATCH MODULE 3: NUMBER CONVERSIONS

CMPSC 111 Introduction to Computer Science I Fall 2016 Lab 8 Assigned: October 26, 2016 Due: November 2, 2016 by 2:30pm

Laboratory. Computer Cycling. Objective. References. Learn about the fetch-execute cycle of computers.

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 104 -Lecture 11 John Y. Park, adapted by C Grasso

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Revision Booklet. Grade 6

************ THIS PROGRAM IS NOT ELIGIBLE FOR LATE SUBMISSION. ALL SUBMISSIONS MUST BE RECEIVED BY THE DUE DATE/TIME INDICATED ABOVE HERE

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

BINARY FOR THE YOUNGER SET

Full file at

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output

Number Bases LESSON TWO. Computer Science. By John Owen

An Introduction to Python (TEJ3M & TEJ4M)

Lesson #64 First Degree Trigonometric Equations

Commas. Review Mini Lesson

EXCEL EXPERT. Starting Excel EXPLORING THE EXCEL WINDOW

Lecture 4: Conditionals

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Programming Lecture 4

This lecture presents ordered lists. An ordered list is one which is maintained in some predefined order, such as alphabetical or numerical order.

CS 142 Style Guide Grading and Details

Computer Programming : C++

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Administration Computers Software Algorithms Programming Languages

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

B. Subject-specific skills B1. Problem solving skills: Supply the student with the ability to solve different problems related to the topics

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

conditional statements

AP Computer Science A Summer Assignment

Simplifying Expressions

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Power School Walk-in Scheduling (Secondary)

[301] Bits and Memory. Tyler Caraza-Harter

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Following is the general form of a typical decision making structure found in most of the programming languages:

Today CISC124. Building Modular Code. Designing Methods. Designing Methods, Cont. Designing Methods, Cont. Assignment 1 due this Friday, 7pm.

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi.

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

INFS 214: Introduction to Computing

CS112 Lecture: Extending Classes and Defining Methods

How to approach a computational problem

CS 351: Design of Large Programs.

Chapter 6 Programming the LC-3

2.2 THE MARIE Instruction Set Architecture

Engr. Joseph Ronald Canedo's Note 1

What a lot of folks might call the class but as we ll see later, it s not entirely accurate.

STEAM Clown Productions. Python lab. Binary Register. STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

Welcome to Technology Class. 7 th Grade: Web Design 8 th Grade: Digital Animation

IT 1204 Section 2.0. Data Representation and Arithmetic. 2009, University of Colombo School of Computing 1

4. Java Project Design, Input Methods

Excel Basics: Working with Spreadsheets

CS 1713 Introduction to Computer Programming II Ch 0 Overview - Problem solving

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

Lesson 2 page 1. ipad # 17 Font Size for Notepad (and other apps) Task: Program your default text to be smaller or larger for Notepad

Slide Set 1. for ENEL 339 Fall 2014 Lecture Section 02. Steve Norman, PhD, PEng

It is recommended that you submit this work no later than Tuesday, 12 October Solution examples will be presented on 13 October.

CSC 121 Spring 2017 Howard Rosenthal

CS 374 Fall 2014 Homework 2 Due Tuesday, September 16, 2014 at noon

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

Transcription:

Lesson 4B Conditionals switch case By John B. Owen All rights reserved 2011, revised 2014

Table of Contents Objectives if else chains, review switch case statements switch case limitations/examples Guidelines for use default case Lesson Summary / Labs Contact Information for supplementary materials

Objectives Students will understand how and when to use the multiple-condition switch/case selection construct in place of the if else chain, or series.

if else chains, review In the previous lesson, you learned about how to make decisions in your program using if (one-way), if else (two-way), as well as chains of if else (multi-way) statements. Sometimes (not always) you can convert an if else chain into a switch case statement.

if else chain, example Say you are trying to convert a character into Morse code, and you want to output the dot/dash equivalent of the letter. For simplicity, let s just use the first few letters of the alphabet.

if else chain, example In Morse code: A =.- B = -... C = -.-. D = -.. E =. F =..-. G = --.

if else chain, example The if else chain in this example is not too bad, but it is only a portion of the alphabet. The entire code would take much more room, and get very long and complicated.

switch case statements A better way to do this would be to set up a multi-way decision process using the switch case statement. In some ways, this is a better, more organized, and more readable way to control multi-way decisions in Java. See the next few slides for the Morse code example using a switch case statement.

switch case statements This switch-case program accomplishes the same thing as the previous ifelse chain program. As you can see, the output is identical. Let s look at it carefully.

switch case statements First of all, the input process is the same a character is input from the keyboard. The process now changes

switch case statements The overall structure of the switch case statement begins with the word switch, followed immediately by a parameter, in this case, let.

switch case statements The let parameter contains the value to be switched into the desired outcome, in this situation, the equivalent Morse code output for the character contained in let.

switch case statements The compiler compares the contents of let to each case in the selector list on the left until it finds a match. Once it finds a match, it jumps the fence, or crosses over the colon to the right side of the statement, and executes the command shown.

switch case statements Once it executes the command, it sees the word break, which causes the whole switch statement to stop. The program then continues on after the end of the switch statement.

switch case statements It is a fairly simple process, really. However, there are some pitfalls that happen sometimes. The most common mistake for beginners is to forget to put the break statement after each line.

No breaks!!!! Look carefully at the different outputs when no breaks are included in the switch statement.

No breaks!!!! What the heck is going on here!!!!

No breaks!!!! The answer is simple once the compiler jumps the fence after finding a match, it executes everything it sees until it sees a break, or until it reaches the end of the statement.

No breaks!!!! In the first example, since the letter G was the last item in the list, there was only one output before the compiler reached the end of the statement, therefore, only one thing was shown.

No breaks!!!! However, the second and third examples show clearly how the no breaks situation played out. The letter F output included the Morse code for both F and G since there was no break after the code for the letter F.

No breaks!!!! Since the letter A was the first match, ALL of the outputs were shown since there were no breaks to stop the falling action.

Why even need breaks!!!! You might be wondering why breaks are even needed, perhaps asking why the Java designers thought it necessary to require them. There is a very good reason flexibility!

Flexibility!!! The option to include breaks or not gives the programmer flexibility to put breaks wherever they are needed, and to take advantage of the falling action feature built into the switch statement.

Flexibility!!! Here is a good example that expands on our Morse code translator program. Suppose you wanted to be able to handle both upper and lower case letters, but have the same Morse code for both. Check out the next slide

Flexibility!!! Here both lower and upper case letters are listed, but the same outcome happens for either one.

Flexibility!!! When the B is switched, the compiler finds the match, jumps the fence, executes the output command, and then stops at the break.

Flexibility!!! When the b is switched, the compiler finds the match, jumps the fence, sees NO statement, but falls until it does see a statement, executes it, and then stops at the break.

switch case limitations The switch case has some limitations, and is not always a better programming construct than the if else chain. In the previous lesson we looked at a grade conversion program, which takes a range of grades and converts them to a letter. This could not be done easily with a switch-case statement.

if else grade conversion Here is the example shown in Lesson 4A. A range of grades from 90 on up results in an A.

switch case equivalent To do this in a switch case statement requires a listing of EVERY SINGLE VALUE IN THE RANGE not a reasonable option since the code would expand to huge proportions, as you can see.

switch case equivalent It is certainly possible to do, but not very practical.

switch case with Strings Strings can now be used in switch statements (as of Java version 7) The basic structure is the same, but the selector list is several strings instead of integers or characters. Study the example on the next slide.

switch case with Strings

switch case guidelines The primary guideline for when it would be good to use this technique is this: - when the value to be switched is a character or integer data type, or a String object no other data types allowed.

switch case guidelines Practically speaking, when the possible list of selector values is fairly short, a switch case statement is a good option The 26 letters of the alphabet is just about as long a list as you would want.

switch case guidelines Bottom line of when to use a switch case statement When using it significantly simplifies your code and makes it more readable to the human eye.

default case Another feature of the switch statement is the case of the default case, the action that happens when no match is found in the selector list. This is usually placed at the end of the list. The next slide shows an example of this technique.

switch case example with default This program is fairly trivial, but demonstrates all of the features of the switch statement, including the default action.

switch case example with default The selector list is simply all of the single digits in base ten, each of which has a comment associated with it. The value 2 has two comments. Notice the strategic placement of the breaks to achieve this.

switch case example with default

No break necessary at the end! Finally, a minor detail Since the last statement in a switch is indeed the last thing that will happen, it is not really necessary to put a break at the end.

Lesson Summary In this lesson, you learned how to use a switch case statement instead of an if else chain, or series. The advantages are that it is : easier to read easier to understand easier to debug easier to maintain

Lesson Summary A minor disadvantage is that decimal values (doubles) cannot be processed as the selector values in a switch statement only integers, characters, and Strings

Lab 4B-1 WAP to calculate the cost of a telephone call when a code number and the length of the call is input. Output the two input values in a sentence along with the cost of the call. Use a switch statement in which the case action calculates by assigning to a variable the cost of the phone call based on the code and number of minutes. The output statement should follow the switch case statement. NO OUTPUT should be produced directly by the switch statement. code table: code rate per minute 1 0.22 2 0.14 3 0.73 4 1.12 5 2.38

Lab 4B-1 Data File ( lab4b1.in ) 2 35 3 10 4 5 5 45 2 23 1 70

Lab 4B-2 Mr. Arthur Einstein, your high school physics teacher, wants a program for English to metric conversions. The input values will be a letter ( P for pounds, F for feet, or M for miles) and a decimal value. The program is to make the appropriate conversions. There are 4.9 newtons in a pound, 3.28 feet in a meter, and 1.61 kilometers in a mile. The switch case action should produce three values assigned to variables: the old unit label based on the input character code, the new unit label based on the desired conversion unit, and the calculated value of the desired conversion. No default case is necessary. Output all values to two decimal places. Again the switch statement should NOT produce directly any output. Code Rate conversions P base unit = pounds Rate: 1 pound = 4.9 newtons F base unit = feet Rate: 1 foot = 0.30488 meters or 1 meter = 3.28 feet M base unit = miles Rate: 1 mile = 1.61 kilometers

Lab 4B-2 Data File: ( lab4b2.in ) M 3.106 P 125 F 120 P 7.2 F 56 M 100

Lab 4B-3 WAP to convert each input hex character into its base ten and binary equivalent. Each input will be one of the 16 HEX characters, 0..F. The switch statement will contain 16 cases, one for each value. Each case action should output three values the original HEX character, the binary value (a string) and the base ten value (an integer). A default case should also be provided for invalid input. 0 = 0000 = 0 1 = 0001 = 1.. 9 = 1001 = 9 A = 1010 = 10 B = 1011 = 11 C = 1100 = 12 D = 1101 = 13 E = 1110 = 14 F = 1111 = 15

Lab 4B-3 Data file: ( lab4b3.in ) A 5 4 C G F 9 Output:

Lab 4B-4 The Saffir/Simpson Hurricane Scale rates hurricanes on a scale of 1 to 5, 1 being the weakest, 5 the strongest. Below is an abbreviated version, with two items listed for each category: wind speed and the expected storm surge water level. Write a switch case statement that will output a sentence describing what to expect with each category. Category 1 Winds 74-95 mph, storm surge of 4-5 ft. Category 2 Winds 96-110 mph, storm surge of 6-8 ft. Category 3 Winds 111-130 mph, storm surge of 9-12 ft. Category 4 Winds 131-155 mph, storm surge of 13-18 ft. Category 5 Winds 155 mph+, storm surge of 18+ feet.

Lab 4B-4 Data File ( lab4b4.in ) 1 3 5 Output:

Lab 4B-5 Expand the String switch example given earlier to include the language selections given, plus three more of your own choosing. Use Google Translate, or any other suitable source to find three other languages to use as selector values. Use data file input instead of keyboard, with lab4b5.in as the data file. Put enough data, in random order, so that all possible outputs will be shown, including the default English greeting.

Lab 4B-5 Here is an example of what the output could be. Be sure to add three different languages of your own.

CONGRATULATIONS! You now understand how to use the switch case multiway conditional statement. The Lesson 5 group will introduce more about the String and Math class methods, as well as how to write your own methods.

Thank you, and have fun! To order supplementary materials for all the lessons in this package, such as lab solutions, quizzes, tests, and unit reviews, visit the O(N)CS Lessons website, or contact me at John B. Owen captainjbo@gmail.com