Programming Fundamentals in Java

Module [102] - Selection Statements

The previous module introduced you to the data manipulation aspects of programming languages. We will now turn our attention to learning to manipulate computations by controlling the flow of execution of a program (i.e. which statements execute, in which order and how many times). This module will focus on conditional statements (branching, decisions) while the next one will introduce iterative statements (repetitions, loops). Once again we will use the Raptor flowchart interpreter to write programs of increasing complexity.

  • Textbook Reading Assignments
  • The following sections of the textbook are assigned for this module.
    • This module does not use the textbook
  • Lecture - Video
  • File Link: YouTube
  • Beware of one mistake on the slides; the "yes / true" and "No / False" labels used on the diagram for the trashcan example have been inadvertently swapped. This results in a rather strange trashcan which requires us to lift the lid even though the lid is already up :) See the fixed slides below. As is usual for longer videos, here are links to the main parts;
  • Lecture - Slides
  • File Link: 102-lecture.ppt
  • These are the slides used in the above video lecture. Please note that the above mistake has been fixed in this version of the slides.

Below, you will find a "wrapup session", which will be used in many of our modules.

  • Wrapup Session - Video
  • File Link: YouTube
  • Wrapup sessions go over the same topics than the previous study material for the module. However, they take a different and supplementary perspective. They focus on each of the programming skills previously identified in our Programming Thought Process video. For each, they stress out how the study material relate to each. It is recommended that you watch these after working with the above material and practice exercises. As is usual for longer videos, here are links to the main parts;

Module Learning Outcomes

In this module, you will develop further your programming skills as follows;

Tracing
Ability to read and trace Raptor programs leveraging conditional expressions and IF-ELSE statements.
Implementing
Ability to write Raptor programs leveraging conditional expressions and IF-ELSE statements.
Testing
Ability to develop tests, on paper for now, that are going to allow us to ensure a Raptor program leveraging IF-ELSE statements and conditional expressions computes the results expected by requirements.
Debugging
Ability to troubleshoot Raptor programs leveraging conditional expressions and IF-ELSE statements.
Designing
Ability to design Raptor programs leveraging conditional expressions and IF-ELSE statements.

Let us start by some relevant resources;

  • Raptor Syntax Slides
  • PDF Link: raptor-2.pdf
  • These slides summarize the main syntax used by Raptor; e.g. mod and rem operators
  • Raptor Control Structures
  • PDF Link: raptor-3.pdf
  • Another hand-out from Dr. Wayne Brown. Focus only on conditional structures for now.

Now, you should be ready to jump in our apprenticeship exercises;

  • A01 - Warming-up
  • File Link: YouTube
  • We are going to start with something really similar to the previous module's questions; write a program which reads two integer values from the user and stores them in two integer variables A and B. You will then display a text-based menu on the screen consisting of the following 4 strings. In order to do so, you will use 4 output statements one after the other:
                    "[1] Compute A + B"
                    "[2] Compute A - B"
                    "[3] Compute A / B"
                    "[4] Compute A * B"
    	  
    Then, you will use an input statement to read a number from the user and store it in the variable named choice.
  • A02 - Improvement - Adding Selection Statement
  • File Link: YouTube
  • Modify the previous flowchart by adding a conditional statement right after reading the choice value from the user. If the choice is equal to the value 1, then display the result of computing the sum of the contents of variables A and B.
  • A03 - Serially Arranged Selection Statements
  • File Link: YouTube
  • We have handled so far one of the possible choices. Complete the previous flowchart so that you handle all the other choices. Important: Make sure that the conditional statements follow each other and are not nested into one another, that is, one conditional statement should not be located inside of the "yes" or "no" part of another conditional statement.
  • A04 - Testing our program so far
  • File Link: YouTube
  • Once you are done coding your previous exercise, test your program by running it several times. Each time you will provide different values for A and B and pick each of the possibilities (1, 2 then 3 and finally 4). Make sure your program behaves correctly in each scenario and fix any bug you discover this way.
  • A05 - Making our program fool-proof
  • File Link: YouTube
  • We covered all the valid choices in the previous exercise but not the case of a user providing us with a number not belonging to the range [1..4]. We want our program to display an error message if the user picks a choice outside of [1..4]. We are going to implement this feature by adding an output statement in the "ELSE" (false) part of the last conditional statement we used in the flowchart for the previous exercise. Once you are done, test your program again using the exact same tests you used in exercise A04. This time you will also try to choose a negative number as option and a number greater than 4. What do you notice? While the program is structurally sound, it doesn't do what we expected it to do. There is a logical bug in it which we are going to fix in the next exercise.
  • A06 - Nested Selection Statements
  • File Link: YouTube
  • We need to restructure our code! It turns out that what we have so far is something like:
    IF choice is 1       
    THEN   display A + B
    ENDIF
    
    IF choice is 2       
    THEN   display A - B
    ENDIF
    
    IF choice is 3       
    THEN    display A / B
    ENDIF
    
    IF choice is 4
    THEN    display A * B
    ELSE    display "I don't understand what you want me to do"
    ENDIF
    	  
    Now, no matter the number we choose, we will trigger one of the IF statements and then the fourth's ELSE part as well. Make sure you understand why this is so. To fix this problem, we need to restructure our code so that the control flow is organized with nested (aka cascading) conditional statements as follows:
    IF choice is 1       
    THEN  display A + B
    ELSE  IF choice is 2       
          THEN  display A - B
          ELSE  IF choice is 3       
                THEN  display A / B
                ELSE  IF choice is 4
                      THEN display A * B
                      ELSE display "Please pick a choice between 1 - 4"
                      ENDIF
                ENDIF
          ENDIF
    ENDIF
    	  
    Implement the above pseudo-code using raptor.
  • A07 - Refactoring - Boolean OR operator
  • File Link: YouTube
  • In our previous conditional statements we used straightforward expressions. We could rewrite the previous flowchart by using a condition featuring the OR logical operator.
    IF choice is lesser strict than 1 OR choice is greater strict than 4        
    THEN    display "Please pick a choice between 1 and 4"
    ELSE    IF choice is 1
            THEN   display A + B
            ENDIF
    
    <... more code here...>
    
            IF choice is 4      
            THEN   display A * B
            ENDIF
    ENDIF
    	  
    Notice how the structure of the code changed, we have now a conditional statement which else part is now containing 4 other conditional statements which are serially-arranged. Implement the above pseudo-code using raptor and test your program comprehensively.
  • A08 - Refactoring - Boolean AND operator
  • File Link: YouTube
  • Rewrite the previous flowchart by replacing the OR operator by a AND operator in the condition of the first IF statement. You will have to modify both parts of the condition to fit this change and keep your program behaving the same. Make sure you test extensively your program using the same test scenarios than you used in exercise A07 and previous.
  • A09 - Palo-Alto Squirrels
  • File Link: YouTube
  • This exercise has been adapted from the JavaBat web site at http://javabat.com/ The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Write a flowchart which is going to ask the user to provide a temperature value (between 0 and 130) and a number summer which will be equal to 0 or 1. Depending on the values that were passed to you by the user, you will determine whether the squirrels are playing or not and display on the screen an appropriate string.
  • B01 - Testing the Palo-Alto Squirrels Program
  • Testing is not an optional part of the programming activity, when your program works once, it does not actually mean anything except that it is ok for this particular set of inputs. You need to select a set a input values (a test harness) which will be sufficient to prove that your code works in all situations. To make sure you test extensively your A09 program, you will write down the tests you have been performing on paper using a table such as the following. Of course, use as many rows as you have test cases in your test harness. Try to build a test harness which can help you detect any kind of bugs in the code. Value for TemperatureValue for SummerExpected OutcomeObserved OutcomeTest Successful?
    ____________________________________________________________________
    | Value for   | Value for | Expected | Observed | Test Successful? |
    | Temperature | Summer    | outcome  | outcome  |                  |
    |_____________|___________|__________|__________|__________________|
    |             |           |          |          |                  |
    |_____________|___________|__________|__________|__________________|
    |             |           |          |          |                  |
    |_____________|___________|__________|__________|__________________|
    |             |           |          |          |                  |
    |_____________|___________|__________|__________|__________________|
    |             |           |          |          |                  |
    |_____________|___________|__________|__________|__________________|
    |             |           |          |          |                  |
    |_____________|___________|__________|__________|__________________|
    	  
  • B02 - Palo-Alto Squirrels, the Next Generation
  • What if the user inputs some values which are not valid (anything outside of [0..130] for the temperature and anything beside 0 or 1 for summer)? A robust program is a program which can handle bad input values from users. Change the code so that it displays an error message when an invalid input is provided for either data Update accordingly the test harness you developed in B01 so that it also tests the above features.
  • B03 - Blackjack or not?
  • This exercise also comes from javabat.com Write a flowchart program which will read two positive integer values from the user and store them in two integer variables A and B. For now, we will assume the user enters positive integer values to your program. You will then display on the screen, the one value out of the two, which is closest to 21 without exceeding it. If both values are over 21, then simply display a message stating that there are no winners this round. If both values are below or equal to 21 and equal, just display a message indicating that both are winners. Develop a test harness to make sure your program works.
  • B04 - Improvement - Robust Blackjack
  • Make sure that from now on you will reject any number entered by the user that is not greater than 0. If the user enters such an integer, just display an error message and do not even test further the values. Update your test harness accordingly.
  • B05 - Speeding Tickets
  • This exercise also comes from javabat.com You are driving a little too fast, and a police officer stops you. Write code to display a message indicating whether you got "No ticket today", a "Small ticket" or a "Big ticket". If speed is 60 or less, the result is "no ticket". If speed is between 61 and 80 inclusive, the result is a small ticket. If speed is 81 or more, the result is a big ticket… Unless it is your birthday! On that day, your speed can be 5 higher in all cases. Your program will start by asking the user for a speed value and whether (value 1) or not (0) it is your birthday. You will then display the outcome.
  • B06 - Robust Speeding Tickets
  • Make sure that from now on you will reject any inappropriate input (different than 0 or 1 for birthday question and refusing negative speed values). If the user enters erroneous values for either input, just display an error message and do not even test further the values. Develop a test harness for the program you developed in B05.