If/Then/Else If Versus Switches

Let’s examine the difference between using If/Then/Else If statements and Switch statements on a basic menu control object.

We are working with the structure of a previously built 4-function calculator that was constructed with If/Then/Else If statements similar to the following:

//Program Name: 4-Function Calculator
//Programmer Name: Your Name
//Programmer Organization: Ferris High School
//Program Date: Fall 2016

import java.util.*;
import java.lang.*;
import java.io.*;

public class calculator{
    public static void main (String[] args) throws java.lang.Exception{
        Scanner menuChoice = new Scanner(System.in);
        System.out.println("Basic Calculator");
        System.out.println("1 - Addition");
        System.out.println("2 - Subtraction");
        System.out.println("3 - Multiplication");
        System.out.println("4 - Division");
        System.out.println("");
        System.out.print("Enter Your Selection_");
        int menu = menuChoice.nextInt();
        
        if (menu == 1){
            //Code for Menu Option 1
        }else if (menu == 2){
            //Code for Menu Option 2
        }else if (menu == 3){
            //Code for Menu Option 3
        }else if (menu == 4){
            //Code for Menu Option 4
        }else{
           //Code if Other Integer Option is Selected
        }
    }
}

Let’s compare the structure of the above with that of a Switch statement similar to the following:

//Program Name: 4-Function Calculator (Switches)
//Programmer Name: Your Name
//Programmer Organization: Ferris High School
//Program Date: Fall 2016

import java.util.*;
import java.lang.*;
import java.io.*;

public class calculator_switches{
    public static void main (String[] args) throws java.lang.Exception{
        Scanner menuChoice = new Scanner(System.in);
        System.out.println("Basic Calculator");
        System.out.println("1 - Addition");
        System.out.println("2 - Subtraction");
        System.out.println("3 - Multiplication");
        System.out.println("4 - Division");
        System.out.println("");
        System.out.print("Enter Your Selection_");
        int menu = menuChoice.nextInt();
        
        switch (menu) {
            case 1:
                {
                    //Code for Menu Option 1
                    break;
                }
            case 2:
                {
                    //Code for Menu Option 2
                    break;
                }
            case 3:
                {
                    //Code for Menu Option 3
                    break;
                }
            case 4:
                {
                    //Code for Menu Option 4
                    break;
                }
            default:
                //Code if Something Different is Entered
                break;
        }
    }
}

Structurally, they both look about the same. Some of the first observations made are similar to “The Switch code is longer.” or “The Switch code has ‘break’ in it a lot.” or finally “I’m going to be thrown off that I don’t need curly braces in the default case of a Switch.”. All of these are good valid observations and concerns. Now, let’s look at why we even consider using the Switch construct.

Why Do We Care?

The primary reason we care is in the general processing speed of the application. When using an If/Then/Else If statement, the application must process each case until it finds the condition that is met. Once that condition is met, the conditional processing stops.

In contrast, a Switch statement creates a jump table that automatically jumps to the correct segment of code to be executed.

When Should I Use What?

If you have a construct that has two different pathways plus a default escape pathway, then an If/Then/Else If is typically considered the best choice.

Example – If/Then/Else If

if (menu == 1){
            //Code for Menu Option 1
        }else if (menu == 2){
            //Code for Menu Option 2
        }else{
            //Code for Items Other Than Menu Options 1 or 2
        }

However, anything beyond two different pathways plus a default escape pathway is better suited by a Switch statement.

Example – Switch

switch (menu) {
            case 1: {
                    //Code for Menu Option 1
                    break;
                }
            case 2: {
                    //Code for Menu Option 2
                    break;
                }
            case 3: {
                    //Code for Menu Option 3
                    break;
                }
            case 4: {
                    //Code for Menu Option 4
                    break;
                }
            default:
                //Code if Something Different is Entered
                break;
        }

 Which is More Efficient?

This is a bit of a loaded question. Some would say that efficiency is defined by how much typing and therefore “coding” is done on the front-end. In this case, the If/Then/Else If code at the top of this post has 755 typed characters while the Switch code has 787 typed characters. By this definition, the Switch code is 95% as efficient as the If/Then/Else If code.

If we define efficiency as speed at which the application runs, it depends on what data is input into the application at runtime. For example, if in the If/Then/Else If the user enters menu choice 1, the application processing time will likely be equal to or slightly faster than that of a Switch since menu choice 1 was the first condition to be checked.

However, if menu choice 4 is selected in the If/Then/Else If code, the application processing time will be longer than that of the Switch code since the conditional statement of menu choices 1, 2, and 3 had to be checked first since they were above the 4th menu choice in the code.

An If – Then – Else Calculator

Today, in Computer Science, we applied the basics of If-Then/Else-If to build a 4-function calculator.

Students were instructed to create a basic calculator application that would first query the user which function they wanted to compute:

1 – Addition
2 – Subtraction
3 – Multiplication
4 – Division

Upon selecting the desired function, the user would be asked to enter the numbers needed to perform the desired calculation. Upon entry of the requested data, the answer would be displayed in plain English.

In the end, the general program looked like the following…

//Program Name: 4-Function Calculator
//Programmer Name: Eric Evans, M.Ed.
//Programmer Organization: Ferris High School
//Program Date: Fall 2016

import java.util.*;
import java.lang.*;
import java.io.*;

public class calculator{
    public static void main (String[] args) throws java.lang.Exception{
        Scanner menuChoice = new Scanner(System.in);
        System.out.println("Basic Calculator");
        System.out.println("1 - Addition");
        System.out.println("2 - Subtraction");
        System.out.println("3 - Multiplication");
        System.out.println("4 - Division");
        System.out.println("");
        System.out.print("Enter Your Selection_");
        int menu = menuChoice.nextInt();
        
        if (menu == 1){
            Scanner firstNumber = new Scanner(System.in);
            System.out.print("Enter the First Number in Your Addition Problem_ ");
            double firstNum = firstNumber.nextDouble();
            Scanner secondNumber = new Scanner(System.in);
            System.out.print("Enter the Second Number in Your Addition Problem_ ");
            double secondNum = secondNumber.nextDouble();
            double solution = firstNum + secondNum;
            System.out.println(firstNum + " plus " + secondNum + " equals " + solution);
        }else if (menu == 2){
            Scanner firstNumber = new Scanner(System.in);
            System.out.print("Enter the First Number in Your Subtraction Problem_ ");
            double firstNum = firstNumber.nextDouble();
            Scanner secondNumber = new Scanner(System.in);
            System.out.print("Enter the Second Number in Your Subtraction Problem_ ");
            double secondNum = secondNumber.nextDouble();
            double solution = firstNum - secondNum;
            System.out.println(firstNum + " minus " + secondNum + " equals " + solution);
        }else if (menu == 3){
            Scanner firstNumber = new Scanner(System.in);
            System.out.print("Enter the First Number in Your Multiplication Problem_ ");
            double firstNum = firstNumber.nextDouble();
            Scanner secondNumber = new Scanner(System.in);
            System.out.print("Enter the Second Number in Your Multiplication Problem_ ");
            double secondNum = secondNumber.nextDouble();
            double solution = firstNum * secondNum;
            System.out.println(firstNum + " times " + secondNum + " equals " + solution);
        }else if (menu == 4){
            Scanner firstNumber = new Scanner(System.in);
            System.out.print("Enter the Total Number of Items You Wish to Divide_ ");
            double firstNum = firstNumber.nextDouble();
            Scanner secondNumber = new Scanner(System.in);
            System.out.print("Enter the Total Number of Groups You Wish the Items Divided Into_ ");
            double secondNum = secondNumber.nextDouble();
            double solution = firstNum / secondNum;
            System.out.println(firstNum + " divided by " + secondNum + " equals " + solution);
        }else{
            System.out.println("Invalid Selection Made.");
            System.out.println("Please Re-Run Program.");
            System.out.println("Make Valid Selection.");
        }
    }
}

In the next class session, we’ll discuss using Switches vs. If-Then / Else-If statements and analyze when those are appropriate and when they are not.

Mousetrap Racers

One of the projects that we do as part of Unit 1 – Motion in Principles of Technology is the “Mousetrap Racers”. These are the kits that come with basic materials for building a race car driven by a mousetrap. However, there are no directions.

In my case, students were working in groups of 2 and had 3 90-minute class periods to prepare their cars. They could use anything from within the classroom on their race cars.

Here are the pictures of their creations…

It Is a Language Other Than English!

It has been a bit of a day, but we now have official word from Texas Education Agency that Computer Science I, Computer Science II, and Computer Science III are all considered as Languages Other Than English and therefore meet the LOTE requirement for students for high school graduation.

At the time of this writing, much of the information on the TEA website is out-of-date and refers to a September 1, 2016 deadline for when these courses no longer count as a LOTE credit. This was what generated much of the confusion.

For us, this means that this course must remain named Computer Science I and not Computer Programming. The difference is that Computer Science I is funded from the State of Texas Technology Applications / Computer Sciences budget while Computer Programming is funded from the Carl D. Perkins-backed Federal Career & Technical Education budget.

Regardless of funding source, we want to do what is in the best interest of our students and offering them an additional “foreign language” alternative is in their best interest. As such, it’s Computer Science I for this year.

Robotics Proposal

Well, I gave myself a real challenge this year: I put down as one of my professional goals for my T-TESS to complete a proposal for expanding our robotics program within the district. I was smart and simply said that I will have a proposal before the School Board and did not say if it was approved or not. Of course, I hope that it would be.

Currently, we have STEM labs at our upper-elementary school, intermediate school, and junior high school. Those labs are based upon the SmartLabs by Creative Learning Systems.

My proposal would be complementary to those STEM labs and allow students to expand their horizons further into the fields related to robotics and automation.

As far as current robotics classes, we have a single Robotics and Automation class at the high school and a single FIRST Tech Challenge robotics team that is also based at the high school.

The proposal would call for us to add a second-year Robotics course to the high school, which would center around curriculum related to the FIRST Robotics Competition program. The first-year Robotics course would center around curriculum related to the FIRST Tech Challenge program.

In addition, we would add two new courses to the junior high school offerings. We would have a Robotics 6 and a Robotics 7/8. The Robotics 6 class would center around curriculum related to the FIRST Lego League program while the Robotics 7/8 class would center around curriculum related to the FIRST Tech Challenge program.

These are absolutely part of the proposal in addition to AP Computer Science I (AP Computer Science – Principles) and AP Computer Science II (AP Computer Science – A).

I have also been brainstorming on if there is a way to incorporate a FIRST Lego League team or teams at our intermediate campus, but as of now, I can’t seem to come up with a way to incorporate that.

A rough schedule would look something like this…

08:00am to 08:53am – Robotics 7/8 (FJH)
08:58am to 09:51am – Robotics 6 (FJH)
09:56am to 10:49am – Conference/Planning (FJH)
11:10am to 12:20pm – Advisory/Lunch (FHS)
12:25pm to 01:55pm (A) – AP Computer Science I (FHS)
12:25pm to 01:55pm (B) – AP Computer Science II (FHS)
02:00pm to 03:30pm (A) – Robotics I (FHS)
02:00pm to 03:30pm (B) – Robotics II (FHS)

As you can see, there is really no time for a transition and class for a single teacher to cover at another campus. Now, I may add in the proposal a future considerations section which would discuss FIRST Lego League and FIRST Lego League Junior at the upper-elementary and the intermediate campus.

Still in its early stages of development and drafting. Time will tell what the final proposal looks like.

Water Bottle Rocketry

We started the school year in Principles of Technology with a bang – more like a blast!

The first project, right out of the gates, was soda-bottle water rockets. This was the introductory project for the course and for Unit 1 – Motion.

The class was broken into self-selected teams of 1 to 3. The class was given a complete 2-liter soda bottle and access to random materials from around the classroom. The teams were given 3 90-minute class sessions to brainstorm and complete their rocket designs.

Upon completion of the designs and following the launches, teams completed force diagrams and a post-launch analysis explaining why their rockets performed the way they did.

Here are the various rockets on the morning of the launches…

Driving Finches

My Robotics class was busy for the past few days working in SNAP! to program the Finches to perform various tasks. We started off easy with some pre-programmed sequential instructions like the following:

screen-shot-2016-09-28-at-7-07-15-pm

We then quickly moved up to more interactive non-linear / non-sequential programming which allowed us to create basic driving functionality. Here were the fruits of their labors:

The students seemed to have fun working with the Finches and it gave them the flexibility to focus solely on the automation programming without having to also worry about the engineering design.

Special thanks to Birdbrain Technologies for loaning us the Finches this year for the students to work with!

All Official & Open House

Well, here we are! It’s Meet the Teacher Night at Ferris High School!

2016-08-18-17-18-55

The 506B computer lab is done with training for the day and prepped and ready for students and their parents.

2016-08-17-15-49-28

The 506A classroom, which is where we will be working on Robotics is coming along. Once we have more equipment, we’ll be thankful for having this space to work with!

2016-08-16-17-22-33

I guess I am all official now with my own name plate on the door. A big shift from where I was at last year with 4th Grade.

Well That Stinks

Well, we were on our way to having both of our vehicles paid down when our 2012 Kia Sedona with 108,000 miles decided to bite the dust.

2016-08-05-19-14-35

The transmission completely failed, the diagnostic computer was hallucinating and many other issues have emerged on this 4-year-old wonder. The repairs were projected to run between $5,000 and $7,000! We’ve already spent nearly $3,000 in various repairs on this thing over the past two years and 50,000 miles (failed oil pump, leaking oil pan, failed oil pressure switch, etc…).

Unfortunately, we purchased it used from CarMax and as such, the factory warranty was void since the full-length only applies to the first owner (according to Kia). I’ve usually been happy with CarMax, but not with this purchase. We’ve done business with them on 8 other vehicles over the years.

As we were very upside-down on this vehicle, we knew our only option was to purchase a vehicle we could roll that substantial negative equity onto. Actually, you don’t roll the negative equity onto the loan, the dealership reduces the price of a vehicle but keep the finance amount at the full price of the vehicle. Unfortunately, this only works on vehicles that are either over-priced or that the dealership wants to get rid of.

In our case, we got a little bit of both. We got two new cars:

2016 Honda Civic

2016-08-06-17-03-39

2016 Honda CR-V

2016-08-06-15-36-29

While we were not exactly planning to go out today to purchase two new vehicles, we were relatively happy with the final outcome. I very impressed with the staff at Rusty Wallis Honda in Dallas.

I will miss my 2005 Honda Pilot, which was the other vehicle involved in the transaction which we had equity in to offset some of the losses from the Kia.