Chapter 4 Selection Statements by bib20662

VIEWS: 4 PAGES: 40

									   Chapter 4: Selection Statements
• To this point, our instructions have all been sequential
   – Each instruction is executed once and in the order provided
• For programs to have some degree of variability (i.e. to
  change their behavior when you run them), the program
  must be able to
   – Alter its flow of instructions
• The sequence of instructions executed is known as the
  flow of control
   – There are 3 forms of flow:
      • Sequential (assignment statements, input, output)
      • Selection (if, if-else, switch)
      • Repetition or Iteration (while loop, do loop, for loop)
          – We examine Selection statements here, Repetition in the next chapter
          Control Behavior
  Sequential instruction          Ordinarily, the program is
  Selection instruction           executed by following each
? Sequential instruction          sequential instruction in order
  Sequential instruction
  Selection instruction               A control statement causes a
  Sequential instruction              “branch” to a new location
  Sequential instruction
  Sequential instruction          Branches may be used to select
  Repetition instruction          between instructions, to skip
  Sequential instruction          over instructions, or to
  …                               repeat instructions

      In all cases, the decision of what to do is
      based on a boolean value (true or false)
     Making Decisions: Booleans
• Thus far, we have ignored boolean variables
   – The idea behind a boolean variable is that it stores one of two
     values, true or false
• When it comes to making a decision so that the program
  can decide what to do next, the decision is based on a
  boolean value or expression
   – That is, an expression or value that evaluates to true or false
• There are three things in Java that evaluate to true or
  false:
   – A boolean variable
   – A boolean expression (one using boolean operations of
     AND, OR, NOT, XOR)
   – A relational expression
               Relational Expressions
 • This type of expression will be more familiar than
   boolean expressions, so we start with these
       – A relational expression is one that uses one or more
         relational operators (greater than, less than, equal to, etc)
       – In Java, we use the following symbols:
                                            All of these operators evaluate two
Operator         Meaning         Example
   <             less than       x<5        expressions (one of the left side of
   >             greater than    x>5        the operator, and one on the right
  <=             less than or    x <= 5     side of the operator), and return a
                 equal to                   boolean value
  >=             greater than    x >= 5
                 or equal to                In addition, all relational expressions
  ==             equal to        x==5       must be placed inside of ( ) as in
  !=             not equal to    x != 5
                                            (x < 5) or else you get a syntax error
Example Relational Expressions
• (age < 21)
  – might be used to see if someone is not yet of
    gambling age
• (sex = = „m‟)
  – see if someone‟s sex (a char) is „m‟ for male
• (answer != „y‟)
  – assume answer is a char that represents a user‟s
    answer to a yes/no question, checks here to see
    if the user did not answer yes
• (score >= 90)
  – might be used to see if someone deserves an A
                  Comparing Strings
• We compare primitives using the 6 relational operators
   – although we won‟t use <, >, <=, >= for booleans
   – we can test to see if (char1 < char2)
• What about comparing two Strings? Can we do
   – (name1 = = name2) or (name1 != name2) ??
      • No, we must use the various String methods to perform comparisons
   – Three useful String methods are
      • equals
      • equalsIgnoreCase
      • compareTo
   – The syntax is string1.methodname(string2) as in
     name1.equals(name)
      • The equals and equalsIgnoreCase return true or false, compareTo
        returns a int value – we will discuss these in more detail in chapter 7
       Comparing Float and Double
• Another problem is how to compare two variables of
  type float or double
   – This seems obvious, just use the relational operator as in
      • (d1 < d2)
   – However, what if you are checking for equality?
      • Imagine that double d1 = 0.33333333 and double d2 = 1.0 / 3.0;
   – What is the value of (d1 = = d2)?
      • False. Why?
   – We have to keep in mind the precision of a value like 1.0 / 3.0
   – The best way to compare floats or doubles is to use an
     approach like this:
      • double DELTA = 0.0001;
   – Then compare d1 and d2 for equality using
      • (d1 – d2 < DELTA)
     More Complex Comparisons
• What if we wanted to compare something more complex
  than just two expressions against each other?
  – For instance, we want to know if either the person‟s age < 21
    OR if the person is female
     • We can‟t do this simply with (age < 21) or with
     • (sex = = „f‟)
     • We would need to perform two comparisons and combine their results
       together
  – We can combine two or more boolean values using logic
    operators
     • OR is one such operator
  – So, we now examine the common logic operations to create
    logical expressions
                       Logical Operators
 • Below are the three common logic operators and
   their “Truth tables”
      – that is, when they are true and when they are false
      – Notice for AND and OR, we compare two boolean
        values, but for NOT, we just use one boolean value

                                                          && is true only
Logic Operation   Java Symbol         Truth Table
     And             &&         False && False = False    when both sides
                                False && True = False     are true
                                True && False = False
                                True && True = True       | | is true if either
      Or               ||       False | | False = False   (or both) sides
                                False | | True = True     are true
                                True | | False = True
                                True | | True = True
                                                          ! swaps values
      Not              !        !True = False
                                                          between true and false
                                !False = True
        More Complex Expressions
• Now that we have seen relational and logical operators,
  we can create complex expressions:
   – (age < 21 | | sex != „m‟)
      • True if the person is under 21 or is not male
   – (answer = = „y‟ | | answer = = „Y‟)
      • True if the user‟s answer is either „y‟ or „Y‟
   – (answer != „n‟ && answer != „N‟)
      • True if the user‟s answer is not „n‟ and is not „N‟
   – (!done && value <= 100 | | again = = „y‟ | | again = = „Y‟)
      • True if the boolean variable done is false and value is equal to or
        under 100, or if the answer again is „y‟ or „Y‟
        Evaluating an Expression
• In the previous example, we had both                     • ()

  && and | | in the expression                             • ++, --
   – Which is evaluated first?
                                                           • !, unary –
• && has a higher precedence than | |
                                                           • *, /, %
   – so && is evaluated before | |
      • If we wanted | | to be evaluated first, we would   • +, -
        have to use ( ) to enforce this order
                                                           • <, <=, >, >=
   – The order of operator precedence is now
     extended from the previous list of                    • = =, !=
     arithmetic operators to include shortcut,             • &&
     relational and boolean opeartors
      • The precedence for all Java operators is given     • ||
        to the left from highest precedence to lowest
                                                           • =, +=, -=, *=, /=
 Example of Evaluating Expressions
• (6 * 3 = = 36 / 2) | | (13 < 3 * 3 + 4) && ! (6 – 2 < 5)
   – (18 = = 18) | | (13 < 9 + 4) && !(4 < 5)
      • perform * and / perform *     perform –
   – true     ||          (13 < 13)   &&     !true
      • perform = =      perform <          perform !
   – true | | false      && false
      •            perform &&
   – true | | false
      • perform | |
   – true
                 Selection Statements
• Now that we have talked about how a computer makes
  decisions, we have to see how we write decision-
  making instructions
  – In order to select what to do, we use one of three forms of
    selection statements in Java
  – These are
     • if
            – if the boolean expression evaluates to true, execute the next instruction,
              otherwise skip it
     • if-else
            – if the boolean expression evaluates to true, execute the next instruction,
              otherwise execute the instruction after the reserved word else
     • switch
            – evaluate an arithmetic or character expression and select between the
              following list, executing the associated instructions
                     The If Statement
• The if Statement is the easiest to
  understand, so we start with it
   – Evaluate an expression (either true
     or false)
   – If true, do the statement otherwise
     skip the statement
      • See the flowchart to the right
   – We will use the if statement if we
     want to decide whether we do
     something or not
      • For instance, ask the user “is it going
        to rain” if so, output “take an
        umbrella”
                                          The syntax is:
                                                 if(expression) statement;
                 if Statement Examples
if (total > amount)
   total = total * (amount + 1);

if (sex = = „m‟)                                  sex is a character
   pay = pay + 500;

if (age >= 21)
   System.out.println("Ok, you can drink");

if (sunny)
   System.out.println("Wear your sunglasses!");   sunny and rainy are
                                                  boolean variables
if (rainy)
    System.out.println("Take an umbrella");

if (x > y)
    x = x * 5 + y;
        Example: Compute Birth Year
import javax.swing.*;
public class Example
{
                                                         • You might recall a
  public static void main(String[ ] args)                  similar version of
  {                                                        this program from
     int age;
     String name = JOptionPane.showInputDialog(            chapter 3
          "Enter your first name");                         – In that chapter, we
     String strAge = JOptionPane.showInputDialog(             just output two
          "Enter your age (as an int value) ");
     String birthday = JOptionPane.showInputDialog(
                                                              possible years, but
          "Have you had your birthday yet? ");                here we test to see
     char birth = birthday.charAt(0);                         if you‟ve had your
     age = Integer.parseInt(strAge);                          birthday yet or not
     int birthyear = 2003 – age;
     if(birth = = „y‟ | | birth = = „Y‟) birthyear --;
                                                            – If so, we subtract
     System.out.println("Your birth year is " +               one from your birth
          birthyear);                                         year
  }
}
        Some Comments on if

• First notice that you must use the reserved
  word “if”, not “If” or “IF”
• Next, the conditional being tested must be
  placed in parentheses following the word if
• There is no ; after if or after the conditional
• The instruction that follows the conditional
  will be executed if the condition is true –
  this instruction is followed by a ;
              The if-else Statement
• Often, we will want to perform
  one of two operations
   – One if the expression is true
   – Another if the expression is false
• We use the if-else statement
   – The if-else statement is known as
     a two-way selection
   – The if statement is known as a
     one-way selection
      • The flowchart is given to the right
                                                The syntax is:
                                                   if(expression)
                  Notice the placement of
                                                       statement1;
                  the ; – there is none after
                  the word else                    else statement2;
                        if-else Examples
if (score >= 60)
    grade = „P‟;                           Use if-else to decide what value
else                                       should be assigned a variable
    grade = „F‟;
                                           Use if-else to decide if an operation
if (number >= 0)
   sqt = Math.sqrt(number);                could/should be performed
else
   System.out.println("Can‟t take the square root of a negative number!");

if (number = = 0)
   System.out.println("Can‟t take reciprocal of 0");
else
   rec = 1.0 / (float) number;

if (age >= 21)
   canGamble = true;
else
   canGamble = false;
             Example: Payroll Program
                                                           • The if-else
import java.io.*;                                            statement is used
public class Payroll
{
                                                             to determine what
  public static void main(String[ ] args) throws IOException formula to use to
  {                                                          compute pay
     BufferedReader key = new BufferedReader(new
            InputStreamReader(System.in));                    – Has the employee
        System.out.print("Enter hours worked ");                earned overtime?
        int hours = Integer.parseInt(key.readLine( ));           • which is paid a
        System.out.print("Enter hourly wages ");                   rate of time and a
        double wages = Double.parseDouble(key.readLine( ));        half for every
        double pay;                                                hour over 40
        if(hours >= 40)
            pay = 40 * wages + (hours – 40) * 1.5 * wages;    – Or not?
            else pay = (double) hours * wages;                   • Which is paid at
        System.out.println("Your earnings are $" + pay);           normal rate
    }
}
             If and Else Clauses
• We will call the instruction after the boolean
  expression as the if-clause
• We will call the instruction after the word else the
  else-clause
   – What if either the if-clause or else-clause needs to
     consist of more than one instruction?
   – Consider this code:
     if(age >= 21)
         System.out.print("You may gamble, how much do you want to bet? ");
        bet = Integer.parseInt(key.readLine( ));
    else
        System.out.print("You are too young to gamble, go home");
        bet = 0;

   – We will get a syntax error, why?
                     Multiple Statements
• In order to place multiple instructions inside the if-clause or the
  else-clause, we must make the multiple statements into a block
     – A block is created by placing the instructions inside of { }
          • { } denote the beginning and ending of a class and the main method
          • but now, things get difficult because we will have to properly balance
            out our { with our } or else we will get syntax errors
          • we will find even more uses for { }

                if(age >= 21)
                {
                    System.out.print("You may gamble, how much do you want to bet? ");
The correct        bet = Integer.parseInt(key.readLine( ));
code from       }
the previous    Else
slide is:       {
                   System.out.print("You are too young to gamble, go home");
                   bet = 0;
                 }
                        Example Program
 import java.io.*;
 public class TemperatureConversion
                                                                                   Note: output
 {                                                                                 is not being
   public static void main(String[ ] args) throws IOException                      formatted!
   {
      double temp2;
      BufferedReader key = new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Enter the temperature to be converted: ");
      int temperature = Integer.parseInt(key.readLine( ));
      System.out.print("Do you want to convert from F to C (1) or C to F (2) ? ");
      char choice = key.readLine( ).charAt(0);
      if(choice = = „F‟ | | choice = = „f‟)
      {
            temp2 = 5.0 / 9.0 * (temp – 32.0);
           System.out.println("The temperature " + temp + " Fahrenheit is " + temp2 + " Celsius");
      }
      else
      {
            temp2 = (9.0 / 5.0) * temp + 32.0;
            System.out.println("The temperature " + temp + " C is " + temp2 + " Fahrenheit");
       }
    }
}
               More Complex Logic
• While the if and if-else statements are simple enough, we
  will require more complex instructions to solve problems
   – Examples:
      • Determine a person‟s tax rate given their salary and marital status
      • Determine a student‟s letter grade given their average
      • Determine a CD‟s interest rate given the investment amount and
        years of investment
      • Determine a student‟s “walking order” in graduation given their
        degree
      • Determine the severity of an illness given the patient‟s body
        temperature
   – All of these problems are related in that there is more than one
     condition being tested so we need more than a single if or if-
     else statement
      • There are multiple ways to solve these types of problems as we will see
                          Example
• To illustrate the example, consider the following
  problem:
   – We want to assign a letter grade based on the student‟s
     class average:
      •   90 –100 : „A‟
      •   80 – 89 : „B‟
      •   70 – 79 : „C‟
      •   60 – 69 : „D‟
      •   0 – 59 : „F‟
   – Can we do this with an if statement or an if-else? No
      • We could solve this with 5 if statements, or with a nested if-
        else statement
   – Nesting means that we have an if statement or an if-else
     statement as the statement inside of the if-clause or the
     else-clause or both
                         Grade Example
  if (average > = 90) grade = „A‟                   Nested approach
     else if (average > = 80) grade = „B‟
        else if (average > = 70) grade = „C‟        Note: indentation is not
             else if (average > = 60) grade = „D‟   needed, its there for program
                else grade = „F‟;                   readability

  if (average > = 90) grade = „A‟;                  Alternate approach – what is
  if (average > = 80) grade = „B‟;                  Wrong with this code?
  if (average > = 70) grade = „C‟;
  if (average > = 60) grade = „D‟;                  If you have a 75%, what is
  if (average > = 0) grade = „F‟;                   Your grade going to be?
We could solve this problem by reordering the
if statements in the opposite order, but the
new code would be inefficient – why?
        More on the Grade Example
• Many students are                                 Wrong code:
                                                    if (average > = 90) grade = „A‟;
  uncomfortable, at least                           if (average > = 80) grade = „B‟;
                                                    if (average > = 70) grade = „C‟;
  initially, with using                             if (average > = 60) grade = „D‟;
  nested if-else structures                         if (average > = 0) grade = „F‟;

   – So instead, they will try to
     use multiple if statements              Better (but not best) code:
      • That leads to the improper        if(average >= 90) grade = „A‟;
        code above to the right           if (average > = 80 && average < 90) grade = „B‟;
                                          if (average > = 70 && average < 80) grade = „C‟;
      • To fix it, we could use
                                          if (average > = 60 && average < 70) grade = „D‟;
        complex conditions as             if (average < 60) grade = „F‟;
        shown to the right
      • Also, be careful not to use
                                       Wrong use of Else:
        final else clauses in separate
                                       if(average >= 90) grade = „A‟;
        if-statements
                                           else if (average >= 80 && average < 90) grade = „B‟;
                                           else if (average >= 70 && average < 80) grade = „C‟;
                                           else if (average >= 60 && average < 70) grade = „D‟;
                                           else grade = „F‟;
import java.io.*;
public class MinOfThree;            Another Example
{
  public static void main(String[] args) throws IOException
  {
      int num1, num2, num3, min = 0;
      BufferedReader key = new BufferedReader(new                           Notice the logic here,
            InputStreamReader(System.in));                                       if num1 < num2,
      System.out.print("Enter three numbers (each on a separate line) ");
      num1 = Integer.parseInt(key.readLine( ));
                                                                                 then we compare
      num2 = Integer.parseInt(key.readLine( ));                                  num1 and num3,
      num3 = Integer.parseInt(key.readLine( ));                                  to see which is
                                                                                 smaller, if num1 <
        if (num1 < num2)
           if (num1 < num3)
                                                                                 num3 then num1
               min = num1;                                                       is smallest (we
           else                                                                  already know
               min = num3;                                                       num1is smaller
         else
            if (num2 < num3)
                                                                                 than num2)
               min = num2;
            else                                                                 if num1 is not less
               min = num3;                                                       than num2, we
         System.out.println("Minimum value is: " + min);
    }
                                                                                 compare num2
}                                                                                and num3
     Even More Complex Examples
• Consider a more complex situation where we need to
  determine a person‟s tax rate
   – Here, the decision is made based not on a single variable (like
     average was previously) but on two variables
      • salary
      • marital_status
   – A ficticious “tax table” is shown below
      • Our code would have to perform two sets of comparisons
            – How?
    If Salary less than      and martial status is    tax rate is
    20000                    single                   20%
    20000                    married                  17%
    40000                    single                   25%
    40000                    married                  22%
    60000                    single                   30%
    60000                    married                  28%
    Two Approaches To Tax Table
                           if(marital_status = = „s‟)
• We could                    if(salary <= 20000) rate = 0.20;
                                  else if(salary <= 40000) rate = 0.25;
  – first compare one of             else rate = 0.30;
    the two variables      else
                               if(salary <= 20000) rate = 0.17;
    and within that               else if(salary <= 40000) rate = 0.22;
    decision, compare                 else rate = 0.28;
    the other variable
                           if(marital_status = = „s‟ && salary <= 20000)
• We could                     rate = 0.20;
                           else if(marital_status = = „m‟ && salary <= 20000)
  – use a complex              rate = 0.17;
    conditional that       else if(marital_status = = „s‟ && salary <= 40000)
    tests both                 rate = 0.25;
                           else if(marital_status = = „m‟ && salary <= 40000)
     • examples shown to       rate = 0.22;
       the right           else if(marital_status = = „s‟ && salary <= 60000)
     • which is better?        rate = 0.30;
                           else if(marital_status = = „m‟ && salary <= 60000)
                              rate = 0.28;
              The Switch Statement
• The switch statement offers a
  shortcut to the nested-if-else            Switch statement syntax:
• However, there are restrictions in        switch (variable)
  its use                                   {
   – Here, a single variable is tested         case value1 : statement;
     against many possible values              case value2 : statement;
                                               …
   – If the variable matches a value, the
                                               case valuen : statement;
     associated instruction(s) is(are)       }
     executed
• The switch statement is easy to           The variable must be either an int
                                            type or a char type and the value
  use but is limited                        is one of the possible values such
   – so you will find that in many          as „a‟, „A‟, „b‟, etc for char values
     situations, you will not be able to
     (or will not want to) use it
                 More on the switch
• Multiple cases can be combined as follows:
   – case value1: case value2: case value3: statement(s);
   – case value4: case value5: statement(s);
   – case value6: case value7: statement(s);
• Unlike the if or if-else statement, you may have multiple
  instructions and do not need to use { } to enclose them
• There is one difficulty with the switch, the variable
  continues to be compared to further cases even after a
  match so you might find multiple statements executing
   – To get around this problem, you will use the break command,
     which is discussed next
         The break Statement
• The reserved word break is used to break
  out of the current control structure
  – Think of it as a premature exit from the current
    block
     • This can be used in numerous control structures
       such as if, if-else, and repetition instructions, but we
       will most commonly (and hopefully only) use it in
       switch statements
  – In the switch statement, it will allow us to exit
    the switch after a case matches so that we will
    not continue to look for additional matches
          The default Statement
• There is also a default statement that will always
  execute
   – This can be thought of as an else for a switch
• Now the switch can be thought of as:
   – If the first case matches, execute the first set of
     instructions else if the second case matches, execute the
     second set of instructions, else…, else if no case
     matches, execute the default statement
• However, for this to work as described, break
  statements must be inserted otherwise it becomes:
   – If the first case matches, execute the first set of
     instructions. If the second case matches, execute the
     second set of instructions. Etc. Execute the default
     statement
                         A switch Example
// assume previous code has assigned grade a letter grade
 switch (grade)
 {
     case „A‟ : case „B‟ : System.out.println("Great job! "); break;
     case „C‟ : System.out.println("Try to do better next time"); break;
     case „D‟ : System.out.println("Not so good, but at least its over! "); break;
     case „F‟ : System.out.println("Bummer, guess you‟ll have to retake it"); break;
     default : System.out.println("Error, illegal grade entered");
 }
• Note the use of break statements and default
     – break so that the switch is exited if any case is found true
     – default as a form of error-handling in case previous code
       computed, or the user input, a wrong value
          • Also notice that we did not check to see if grade was a lower case
            letter, we will assume the code that assigned the grade only assigns
            upper case letters
                – but if grade = = „a‟, the default statement executes – this is actually
                  appropriate, „a‟ is not a legal letter grade
           When to Not Use switch
• The switch seems simpler than the
  if or if-else
   – no need for nesting for one                     int avg = Math.round(average);
                                                     switch(avg)
• However                                            {
                                                       case 100 : case 99 : … case 90 :
   – if you have a lot of values to                       grade = „A‟; break;
                                                       case 89 : case 88 : … case 80 :
     compare the switch statement can                     grade = „B‟; break;
     quickly get out of hand                           case 79 : case 78 : … case 70 :
                                                          grade = „C‟; break;
      • Consider the skeletal code to the right        case 69 : case 68 : … case 60 :
      • Too many possible conditions                      grade = „D‟; break;
                                                       default grade = „F‟
          – you would have to type every int value   }
            from 100 down to 60!

• Its best to use the nested if-else
            Also remember that you cannot use the switch if you have
            multiple variables or non int/char type variables to test
     More Complex switch Usage
• We can use the switch                 switch(marital_status)
                                        {
  with other statements                    case „s‟ :
                                             if(salary <= 20000)
  – Here we have two sets of                       rate = 0.20;
    code that use the switch to                 else if(salary <= 40000)
    help us with the tax table                        rate = 0.25;
    problem from earlier                          else rate = 0.30;
                                               break;
  – Notice that we still use the            case „m‟ :
    nested if-else for comparing               if(salary <= 20000)
    salary                                         rate = 0.17;
     • since there are too many                  else if(salary <= 40000)
       possible values for salary                     rate = 0.22;
                                                   else rate = 0.28;
     • but we can use switch for
                                                break;
       marital_status since there are
                                            default : System.out.println
       only two possibilities and
                                                   ("Illegal value for marital status");
       marital_status is a char type
                                        }
 Which Statement Should You Use?
                              • If there is only one action, then use
• When it comes to              the if statement
  selection, you have         • If two actions, one if the condition
  five possibilities:           is true, one if the condition is false,
   – if statement               then use the if-else statement
   – if-else statement        • If you have a series of possibilities,
   – group of if statements     which should you use?
   – nested if-else
     statement
                                 – Switch statement if the possibility is
                                   based on a single variable and the
   – switch statement
                                   variable is an integral data type
                                   (integer, character or a user defined
                                   type that is ordinal)
                                 – Otherwise, use the nested if-else
                                   statement
        Common Syntax Errors
• Not placing your condition in ( )
• Forgetting to place blocks of instructions   if(a < b)
                                                  a++;
  in { } marks: consider the code to the          b--;
  right which causes an else without if        else b++;
  syntax error
• Placing a ; in the wrong place (for
  instance, after the if, else or after the
  condition
• Improperly nesting your if-else structure
  so that the conditions and else clauses do
  not match up
• Using the wrong type of variable in a
  switch statement
                Other Errors
• Using = instead of = = for equality – this may not
  cause a syntax error, but will never work correctly
• Using = = for String or other object comparisons –
  this will never work correctly!
• Using the wrong logic for your nested structures
  (this will be a common problem for introductory
  students)
• Forgetting to use break statements in your switch
  code
• Using improper logic in your conditions –
  especially when you have to deal with complex
  conditions using &&, | |, and !

								
To top