Semester Review – Computer Science

When my Computer Science I students return in January, I will be giving them the following assignment:

Create a JAVA application that has users guess a pre-selected number as a game. The application should provide the rules of the game which state a random number between 0 and 100 will be chosen and users will be given a maximum of 20 guesses.

When asking the user for each guess, the application should indicate which guess of the 20 the user is on and whether their guess was too high or too low.

If the user guesses the solution in under 20 guesses, they will be congratulated and given the number of guesses it took for them to arrive at the solution.

If the user exceeds the maximum number of allowed guesses, they will be told they have exceeded the allowed number of guesses and will be provided with what the solution was.

While there are numerous ways this problem could be tackled, here is one possible solution that is similar to what I would expect at this point in the year:

//Program Name: Guess My Number
//Programmer Name: Eric Evans, M.Ed.
//Programmer Organization: Ferris High School
//Program Date: Spring 2016
import java.util.*;
import java.lang.*;
import java.io.*;
public class guessNumber{
    public static void main (String[] args){
        System.out.println("Welcome to the Number Guessing Game");
        System.out.println("");
        System.out.println("I will pick a number at random and your job is to guess the number that I have chosen.");
        System.out.println("The number will be between 0 and 100. I will give you clues after each guess.");
        System.out.println("You will have up to 20 guesses to guess my number.");
        System.out.println("");
        Scanner ready = new Scanner(System.in);
        System.out.print("Are you ready to start? (Y or N)");
        String readyGo = ready.next();
        String readyGoUC = readyGo.toUpperCase();
        if (readyGoUC.equals("Y")){
            double randomNumber = Math.random() * 100;
            int randomNumberInt = (int)randomNumber;
            Scanner myGuessInput = new Scanner(System.in);
            System.out.print("What is your first guess? ");
            int myGuess = myGuessInput.nextInt();
            while(readyGoUC.equals("Y")){
                for (int score = 1; score < 20; score++){
                    if(randomNumberInt > myGuess){
                        System.out.println("Too Low. Try a Higher Number");
                        myGuessInput = new Scanner(System.in);
                        System.out.print("What is your #" + score + " guess? ");
                        myGuess = myGuessInput.nextInt();     
                    }else if(randomNumberInt < myGuess){
                        System.out.println("Too High! Try a Lower Number");
                        myGuessInput = new Scanner(System.in);
                        System.out.print("What is your #" + score + " guess? ");
                        myGuess = myGuessInput.nextInt();
                    }else if(randomNumberInt == myGuess){
                        System.out.println("");
                        System.out.println("Congratulations! You Guessed my Number!");
                        System.out.println("");
                        System.out.println("Number of Guesses = " + score);
                        System.out.println("");
                        System.out.println("Exiting Program");
                        System.exit(0);
                    }
                }
                System.out.println("");
                System.out.println("You have exceeded the maximum number of guesses.");
                System.out.println("");
                System.out.println("The number I picked was " + randomNumberInt);
                System.exit(0);
            }
        } else{
            System.out.println("Thank you for playing.");
            System.out.println("Exiting Program");
            System.exit(0);
        }
    }
}

This solution utilizes several of the skills covered in the first semester of Computer Science I including the use of character, string, integer, double, and scanner variable types. In addition, the toUpperCase and equals methods of the String class are used as is the random method of the Math class.

Also, in this possible solution, if/else, for, and while statements are all utilized along with various Boolean operators.

Coding Bat – mixStart

This exercise requires that the program return the value of true if what has been entered is a 3-letter word with the 2nd and 3rd letters being “ix”.

Here is the code that you start with:

public boolean mixStart(String str) {
  
}

As you can see, we have a String variable named “str”.

public boolean mixStart(String str) {
  if (str.length() < 3) return false;
  String two = str.substring(1, 3);
  if (two.equals("ix")) {
    return true;
  } else {
    return false;
  }
}

In the solution, first check the length of the statement using the length function of the String class. If the length is less than 3 characters long, the program stops running and returns “false”.

Assuming that the value of “str” is at least 3 characters long we move to using the substring function of the String class to create the value to be assigned to variable “two”. The substring starts at index 1 and stops at index 3. This means that the variable “two” will only have the 2nd and 3rd letters of the variable “str”.

We now begin the analysis of the variable “two”. If it is “ix” then the program returns true. However, if it is NOT “ix” then the program returns false.

You will notice that the comparison is being made using the following:

if (two.equals("ix")) {

Some have asked if we could use something similar to the following:

if (two == "ix") {

While this looks like this would work in comparing a string variable to an existing string, we must use the equals function of the String class to determine if two strings are equivalent.

Traditional boolean operators such as == and != do not work when comparing strings.

Coding Bat – parrotTrouble

This exercise requires that the program return the value of true if you are in “trouble” and a value of false if you are not in “trouble”. You are in trouble if the parrots are talking before 07:00am or after 08:00pm.

Here is the code that you start with:

public boolean parrotTrouble(boolean talking, int hour) {
  
}

As you can see, we have a boolean named talking and an integer named hour.

public boolean parrotTrouble(boolean talking, int hour) {
  return (talking && (hour < 7 || hour > 20));
}

The solution uses a nested boolean to see if the time is before 7 OR after 20. It is simultaneously looking to see if the parrots are talking.

We are using an AND to bridge these two boolean statements together because if the parrots are NOT talking, we can’t be in trouble regardless of the time of day.

Coding Bat – sumDouble

This exercise requires that the program return the sum of two provided numbers. If the two provided numbers are the same, the sum is to be doubled.

Here is the code that you start with:

public int sumDouble(int a, int b) {
  
}

As you can see, we have two integers (a and b) that have been declared.

public int sumDouble(int a, int b) {
  int sum = a + b;
  if (a == b) {
    sum = sum * 2;
  } 
  return sum;
}

In this solution, we have created an integer variable named “sum” which has the value of “a” added to “b”.

We then move to a conditional statement. If “a” equals “b”, the variable “sum” is multiplied by 2. We only enter this instruction if “a” and “b” are equal to each other.

Following either entry of the IF statement or bypassing it, we display the value of the variable “sum”.

Coding Bat – sleepIn

This exercise requires that the program return “true” if it is OK to sleep in on a given day. The rules are that you can sleep-in on a day that is not a weekday or on a vacation day.

Here is the code that you start with:

public boolean sleepIn(boolean weekday, boolean vacation) {
 
}

As you can see, we have a boolean named weekday and a boolean named vacation.

public boolean sleepIn(boolean weekday, boolean vacation) {
  if (!weekday || vacation) {
    return true;
  }  
  return false;
}

The solution uses a boolean conditional of if the value is NOT a weekday OR a vacation, it will return true, otherwise it will return false.

Quick Hands-On Primer to OOP in JAVA

JAVA Programming Language LogoAs a quick hands-on primer to object oriented programming in JAVA, I am going to work with my students to create a basic program that asks the user for their first name and then to select a language they want to be greeted in. The program will then produce the appropriate greeting in the language selected.

In this primer, we will be working with two files (primary.java and secondary.java). The primary.java file will contain our main class of the application while the secondary.java file will be handling all of our active “processing”.

//Program Name: OOP Primer (File 1 of 2)
//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 primary{
    public static void main (String[] args){
        System.out.println("** Greetings Generator **");
        Scanner firstName = new Scanner(System.in);
        System.out.print("What Is Your First Name?_ ");
        String userFirstName = firstName.next();
        System.out.println("Thank you, " + userFirstName);
        Scanner language = new Scanner(System.in);
        System.out.println("Select the Language for Your Greeting");
        System.out.println("1 - English");
        System.out.println("2 - Spanish");
        System.out.println("3 - German");
        System.out.println("4 - Pig Latin");
        System.out.print("Language Selection: _ ");
        int greetingLanguage = language.nextInt();
        System.out.println("");
        secondary myGreeting = new secondary (userFirstName, greetingLanguage);
        System.out.println(myGreeting.greeting);
    }
}

In lines 13 – 16, we are working with receiving the first name of the user.

In lines 17 – 25, we are working with receiving the language the user would like to be greeted in.

Line 26 is the one line that confuses my students to most. This is the heart of Object Oriented Programming. This line is creating a new object named “myGreeting” which is based upon the variables userFirstName and greetingLanguage that is processed in the secondary.java file.

Line 27 is the output of a method we created in the secondary.java file named “greeting”. You can see what that method is by reading the secondary.java file.

//Program Name: OOP Primer (File 2 of 2)
//Programmer Name: Eric Evans, M.Ed.
//Programmer Organization: Ferris High School
//Program Date: Fall 2016

public class secondary{
    public String greeting;
    public secondary (String userFirstName, int greetingLanguage)
    {
        switch (greetingLanguage) {
            case 1:
                greeting = "Hello " + userFirstName;
                break;
            case 2:
                greeting = "Hola " + userFirstName;
                break;
            case 3:
                greeting = "Hallo " + userFirstName;
                break;
            case 4:
                greeting = "Ellohay " + userFirstName;
                break;
            default:
                greeting = "Invalid Selection";
                break;
        }
    }
}

In line 7, we created a public string variable named “greeting”. A public variable is one that can be passed between files within the application. Think of it as a “global” variable.

In line 8, we are establishing which variables we should be receiving from any files. In this case, that is the string variable “userFirstName” and the integer variable “greetingLanguage”.

Lines 11 – 26 utilize a switch for a conditional statement based on the integer value of “greetingLanguage” variable. In those lines, you can see that we declare the value of the variable “greeting” for each case. This is the method that is called-up in line 27 of the primary.java file.

For the record, I require my students to encase all of the applications within a loop to ask the user if they wish to run the application again or to exit. As this requirement would only impact the primary.java file, here is the completed code for that file:

//Program Name: OOP Primer (File 1 of 2)
//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 primary{
    public static void main (String[] args){
        int runAgain = 1;
        while (runAgain == 1){
            System.out.println("** Greetings Generator **");
            Scanner firstName = new Scanner(System.in);
            System.out.print("What Is Your First Name?_ ");
            String userFirstName = firstName.next();
            System.out.println("Thank you, " + userFirstName);
            Scanner language = new Scanner(System.in);
            System.out.println("Select the Language for Your Greeting");
            System.out.println("1 - English");
            System.out.println("2 - Spanish");
            System.out.println("3 - German");
            System.out.println("4 - Pig Latin");
            System.out.print("Language Selection: _ ");
            int greetingLanguage = language.nextInt();
            System.out.println("");
            secondary myGreeting = new secondary (userFirstName, greetingLanguage);
            System.out.println(myGreeting.greeting);
            System.out.println("");
            Scanner runItAgain = new Scanner(System.in);
            System.out.println("Would You Like to Run Again");
            System.out.print("1 - Yes  /  0 - No : _ ");
            runAgain = runItAgain.nextInt();
        }
        System.out.println("");
        System.out.println("Program Complete - Exiting");
    }
}

As you can see, the code to run the application again, adds lines 12 to 13 & lines 30 to 37.

Following is brief video of what the output should look like with the program compiled and executed.

Odd or Even Number

I recently gave a single-class project to my Computer Science I students with the following guidelines:

  • The user is asked to enter a valid integer between -2,147,483,647 and 2,147,483,647
  • The program will then clearly output whether the entered number is an odd number or an even number
  • Following the calculation, the user will be asked if they want to run the program again or exit

The odd/even calculation can be run similar to the following:

//Program Name: Blue Pelican Java Lesson 09 (Project)
//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 project9
{
    public static void main (String[] args){
        Scanner numberInput = new Scanner(System.in);
        System.out.print("Enter an integer up to 2,147,483,647: _ ");
        int numberOddEven = numberInput.nextInt();
        double check = numberOddEven % 2;
        if (check == 0){
            System.out.println("The integer " + numberOddEven + " is even");
        }else{
            System.out.println("The integer " + numberOddEven + " is odd");
        }
    }
}

This will run the calculation only once. It is using a conditional statement based upon modulus division. If the number entered is an even number, when it is divided by 2 the modulus (remainder) is 0. If the number entered is an odd number, when it is divided by 2, the modulus (remainder) is 1. From here, this is a simple boolean statement (line 18).

Now, we’ll look at creating the loop:

//Program Name: Blue Pelican Java Lesson 09 (Project)
//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 project9
{
    public static void main (String[] args){
        int runAgain = 1;
        while (runAgain == 1){
            //* * * * * * * * * * * * * * * * * * * * *
            // LINES 13 TO 21 FROM ABOVE BLOCK OF CODE
            //* * * * * * * * * * * * * * * * * * * * *
            Scanner runItAgain = new Scanner(System.in);
            System.out.println("");
            System.out.println("Do You Want to Run Again?");
            System.out.println("1 - Yes, Run Again");
            System.out.println("2 - No, Exit Program");
            runAgain = runItAgain.nextInt();
        }
        System.out.println("Exiting Program. Thank you.");
    }
}

As you can see, we chose to employ a while loop. The initial variable was declared on line 13, which allows us to enter the loop on line 14.

Lines 18 through 22 are asking the user is the want to run the program again. Line 23 assigns the value that was entered to the “runAgain” variable. If the value entered is 1, the while loop runs again. If it is anything other than 1, the loop is exited and line 25 runs.

The final program could look similar to the following:

//Program Name: Blue Pelican Java Lesson 09 (Project)
//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 project9
{
    public static void main (String[] args){
        int runAgain = 1;
        while (runAgain == 1){
            Scanner numberInput = new Scanner(System.in);
            System.out.print("Enter an integer up to 2,147,483,647: _ ");
            int numberOddEven = numberInput.nextInt();
            double check = numberOddEven % 2;
            if (check == 0){
                System.out.println("The integer " + numberOddEven + " is even");
            }else{
                System.out.println("The integer " + numberOddEven + " is odd");
            }
            Scanner runItAgain = new Scanner(System.in);
            System.out.println("");
            System.out.println("Do You Want to Run Again?");
            System.out.println("1 - Yes, Run Again");
            System.out.println("2 - No, Exit Program");
            runAgain = runItAgain.nextInt();
        }
        System.out.println("Exiting Program. Thank you.");
    }
}

 

A Number Systems Calculator

I have assigned a single-day project for my Computer Science students to create a number systems calculator to wrap-up our discussions on numbering systems.

In this project, students have to create a converter that first asks which number system the original number is from (Decimal, Binary, Octal, or Hexadecimal). It will then ask for the number and will output the equivalent values in the other 3 number systems with each clearly labeled.

The students are starting with the following code from Github…

//Program Name: Number Converter
//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 converter{
    public static void main (String[] args) throws java.lang.Exception{
        Scanner menuChoice = new Scanner(System.in);
        System.out.println("Number Converter");
        System.out.println("");
        System.out.println("Which number system are you converting from?");
        System.out.println("1 - Decimal - Base 10");
        System.out.println("2 - Binary - Base 2");
        System.out.println("3 - Octal - Base 8");
        System.out.println("4 - Hexadecimal - Base 16");
        System.out.println("");
        System.out.print("Enter Your Selection_ ");
        int menu = menuChoice.nextInt();
        
        switch (menu) {
            case 1:
                {
                    Scanner myNumber = new Scanner(System.in);
                    System.out.print("Enter Your Decimal (Base 10) Number_ ");
                    int myDecimalNumber = myNumber.nextInt();
                    String myDecimalNumberBin = (Integer.toString(myDecimalNumber, 2));
                    String myDecimalNumberOct = (Integer.toString(myDecimalNumber, 8));
                    String myDecimalNumberHex = (Integer.toString(myDecimalNumber, 16));
                    System.out.println("The Decimal Number " + myDecimalNumber + " is equal to the following:");
                    System.out.println("");
                    System.out.println("Binary (Base 2) = " + myDecimalNumberBin);
                    System.out.println("Octal (Base 8) = " + myDecimalNumberOct);
                    System.out.println("Hexadecimal (Base 16) = " + myDecimalNumberHex);
                    break;
                }
            case 2:
                {
                    Scanner myNumber = new Scanner(System.in);
                    System.out.print("Enter Your Binary (Base 2) Number_ ");
                    String myBinaryNum = myNumber.nextLine();
                    int myBinaryNumber = (Integer.parseInt(myBinaryNum,2));
                    String myBinaryNumberDec = (Integer.toString(myBinaryNumber, 10));
                    String myBinaryNumberOct = (Integer.toString(myBinaryNumber, 8));
                    String myBinaryNumberHex = (Integer.toString(myBinaryNumber, 16));
                    System.out.println("The Binary Number " + myBinaryNumber + " is equal to the following:");
                    System.out.println("");
                    System.out.println("Decimal (Base 10) = " + myBinaryNumberDec);
                    System.out.println("Octal (Base 8) = " + myBinaryNumberOct);
                    System.out.println("Hexadecimal (Base 16) = " + myBinaryNumberHex);
                    break;
                }
            case 3:
                {
                    //Code for Menu Option 3
                    break;
                }
            case 4:
                {
                    //Code for Menu Option 4
                    break;
                }
            default:
                System.out.println("Invalid Selection");
                break;
        }
    }
}

With the given information, they should be able to easily code cases 3 and 4 of the problem.

Students are asked to test their solutions using the following test case:

Base 10 Base 2 Base 8 Base 16
42 101010 52 2A

As you can see, the test case all comes down to a matter of “Life, the Universe and Everything!”.

Here is a possible final solution:

//Program Name: Number Converter
//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 converter{
    public static void main (String[] args) throws java.lang.Exception{
        Scanner menuChoice = new Scanner(System.in);
        System.out.println("Number Converter");
        System.out.println("");
        System.out.println("Which number system are you converting from?");
        System.out.println("1 - Decimal - Base 10");
        System.out.println("2 - Binary - Base 2");
        System.out.println("3 - Octal - Base 8");
        System.out.println("4 - Hexadecimal - Base 16");
        System.out.println("");
        System.out.print("Enter Your Selection_ ");
        int menu = menuChoice.nextInt();
        
        switch (menu) {
            case 1:
                {
                    Scanner myNumber = new Scanner(System.in);
                    System.out.print("Enter Your Decimal (Base 10) Number_ ");
                    int myDecimalNumber = myNumber.nextInt();
                    String myDecimalNumberBin = (Integer.toString(myDecimalNumber, 2));
                    String myDecimalNumberOct = (Integer.toString(myDecimalNumber, 8));
                    String myDecimalNumberHex = (Integer.toString(myDecimalNumber, 16));
                    System.out.println("The Decimal Number " + myDecimalNumber + " is equal to the following:");
                    System.out.println("");
                    System.out.println("Binary (Base 2) = " + myDecimalNumberBin);
                    System.out.println("Octal (Base 8) = " + myDecimalNumberOct);
                    System.out.println("Hexadecimal (Base 16) = " + myDecimalNumberHex);
                    break;
                }
            case 2:
                {
                    Scanner myNumber = new Scanner(System.in);
                    System.out.print("Enter Your Binary (Base 2) Number_ ");
                    String myBinaryNum = myNumber.nextLine();
                    int myBinaryNumber = (Integer.parseInt(myBinaryNum,2));
                    String myBinaryNumberDec = (Integer.toString(myBinaryNumber, 10));
                    String myBinaryNumberOct = (Integer.toString(myBinaryNumber, 8));
                    String myBinaryNumberHex = (Integer.toString(myBinaryNumber, 16));
                    System.out.println("The Binary Number " + myBinaryNumber + " is equal to the following:");
                    System.out.println("");
                    System.out.println("Decimal (Base 10) = " + myBinaryNumberDec);
                    System.out.println("Octal (Base 8) = " + myBinaryNumberOct);
                    System.out.println("Hexadecimal (Base 16) = " + myBinaryNumberHex);
                    break;
                }
            case 3:
                {
                    Scanner myNumber = new Scanner(System.in);
                    System.out.print("Enter Your Octal (Base 8) Number_ ");
                    String myOctalNum = myNumber.nextLine();
                    int myOctalNumber = (Integer.parseInt(myOctalNum,8));
                    String myOctalNumberDec = (Integer.toString(myOctalNumber, 10));
                    String myOctalNumberBin = (Integer.toString(myOctalNumber, 2));
                    String myOctalNumberHex = (Integer.toString(myOctalNumber, 16));
                    System.out.println("The Octal Number " + myOctalNumber + " is equal to the following:");
                    System.out.println("");
                    System.out.println("Decimal (Base 10) = " + myOctalNumberDec);
                    System.out.println("Binary (Base 2) = " + myOctalNumberBin);
                    System.out.println("Hexadecimal (Base 16) = " + myOctalNumberHex);
                    break;
                }
            case 4:
                {
                    Scanner myNumber = new Scanner(System.in);
                    System.out.print("Enter Your Hexadecimal (Base 16) Number_ ");
                    String myHexNum = myNumber.nextLine();
                    int myHexNumber = (Integer.parseInt(myHexNum,16));
                    String myHexNumberDec = (Integer.toString(myHexNumber, 10));
                    String myHexNumberBin = (Integer.toString(myHexNumber, 2));
                    String myHexNumberOct = (Integer.toString(myHexNumber, 8));
                    System.out.println("The Hexadecimal Number " + myHexNumber + " is equal to the following:");
                    System.out.println("");
                    System.out.println("Decimal (Base 10) = " + myHexNumberDec);
                    System.out.println("Binary (Base 2) = " + myHexNumberBin);
                    System.out.println("Octal (Base 8) = " + myHexNumberOct);
                    break;
                }
            default:
                System.out.println("Invalid Selection");
                break;
        }
    }
}

 

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.