Docstoc

selection

Document Sample
selection Powered By Docstoc
					Control Structures


Objectives

        To understand what control structures are and the need for them.
        To understand the two types control flow – selection and iteration.
        To understand selection statements – if, if/else and switch.
        To understand iterative statements – while, do/while, and for.




Introduction


The order in which statements are executed in programs is determined by the controls to which each
statement is subjected. Unless otherwise specified, the execution of a program proceeds in a linear fashion,
from the first statement to the last; no statement is skipped, and none is repeated. Figure 4.1 shows what
happens when statements are executed in sequence; each statement represented by S, is executed in the
order in which each is written.


                                    S1


                                    S2


                                    S3



                                    Si




                  Figure 4.1Program statements executed in sequence.



The invocation of methods do not constitute an altering of the control flow, but rather it is an expansion of
the statement call, in which case the statement is expanded by the method definition. If we let M represents
a method instead of a single statement, as shown in Figure 4.2, then when the method is called, it simply
executes its statements, and then re-enters the original linear formation of statements.
          Original Linear Formation


                    S1



                  M()

                                                           S1
                                                            :          Definition of method M()
                                                           Si




                     S3



                    Si


             Figure 4.2 Method M is called from the original linear formation



Control structures seek to alter the flow of program statements within a given piece of code. This is carried
out using two control structures - selection and iteration.



Selection Statements
Selection statements are those statements that allow for choice to be made. The decision for making a
choice is based on the result of a conditional expression. Figure 4.3 represents a decision making process.
In this Figure, notice that the result of the conditional expression – representing a decision – is one of the
Boolean values, true or false.




                                                                   true
                             conditional expression


                                false

             Figure 4.3 Symbol representing selection.

There are two basic forms of selection statements in Java. These are the if statement and the switch
statement.
The if Statements
As we said earlier, the if statement allows us to make choice. The statement has two forms, namely, if
without an alternate choice, and if with alternate choice, symbolized by the keyword else. The word if is
also a keyword. The general format of the if statement without an alternate choice is as follows:

         if ( conditional_expression )
               a_single_statement;

         or

         if ( conditional_expression )
         {
               Two or more statements;
         }

The interpretation of this form of the if statement is this, if the conditional expression evaluates to true,
then the statement or the block of statements that follow the condition will be executed. If the result is false,
then the statement or block of statements that follow the condition will be skipped. Figure 4.4 shows
conceptually, the format of the if statement that does not have an alternate choice.



                                                                   true
                               condition expression                                      S


                                false

Figure 4.4 An if statement without alternate choice

The following is an example of its usage:

         if ( 30 > 25)
                System.out.println(“That is correct”);

Where the word if is the keyword, and 30 > 25 is the conditional expression that is being tested. In this
case the condition evaluates to true, and so the print statement is executed.

Example 4.1

    The cost of an international telephone call is a flat fee of $4.00 for up to the first 5
    minutes, and $0.25 per minute for any additional minutes. Write a class
    definition called Telephone that accepts an integer, representing the number of
    minutes used. Provide a method called calculateBill that calculates customers,
    bill.
         Name of class Telephone
         Constants:
               o Flat rate $4.00
               o Cost per additional minutes 0.25
               o Maximum number of minutes at flat rate, 5
         Instance variable – the minutes
         Constructor:
               o Accepts number of minutes spent on each call
         Method calculateBill()
               The total cost of a call is the flat rate up to 5 minutes, and 25 cents * any
               additional minutes. The condition for the additional expense must be based on
               the relation between the number of minutes used, and the five minutes for the
               flat rate. That is:

              if (minutes > 5 )
                   then charge the additional cost.

Listing 4.1 shows the class Telephone. Lines 3 – 4 set up the class constants. Lines 5 – 6 declare the
instance variables. The constructor which receives a single value representing the number of minutes used,
spans Lines 7 – 11. Notice that the initial charge is $4.00. Any additional minutes must be charged. The
method calculateBill(), shown on Lines 12 – 15, determines if the number of minutes used, exceed the
maximum number of minutes at the flat rate. Notice also that the test does not indicate an alternate choice.

    1. public class Telephone
    2. {
    3.    private final static float        FLAT_RATE   = 4.0F,
                                            RATE        = 0.25F;
    4.        private final static int      MAX_MINUTES = 5;
    5.        private int minutes;
    6.        private float charges;

    7.        public Telephone(int minutes)
    8.        {
    9.           this.minutes = minutes;
    10.          charges = FLAT_RATE;
    11.       }

    12.       public void calculateBill()
    13.       {
    14.          if (minutes > MAX_MINUTES)
                          charges = charges + (minutes - MAX_MINUTES)*RATE;
    15.       }

    16.       public float getBill()
    17.       {
    18.           return charges;
    19.      }
    20. }

Listing 4.1 Implementing the if without an alternative choice.



Listing 4.2 shows a typical test class. Line 10 simply creates a customer object that spends m number of
minutes on a call. Line 11 calls the calculate method, and Line 12 calls the getBill() method in order to
print the bill for the customer.

    1. import java.text.NumberFormat;
    2. import java.util.Scanner;

    3. public class TestTelephone
    4. {
    5.    public static void main(String[] arg)
    6.    {
    7.         NumberFormat nf = NumberFormat.getCurrencyInstance();
    8.         Scanner s = new Scanner (System.in);
    9.         int m = s.nextInt();
    10.        Telephone t = new Telephone(m);
    11.        t.calculateBill();
    12.        System.out.println("Your bill is " + nf.format(t.getBill()));
    13.        s.close();
    14.   }
    15. }

    Listing 4.2 Test class for the class Telephone.

    If two or more statements depend on the outcome of a conditional expression, then those statements
    form a block, and they must be enclosed within curly braces. For instance, in the program segment
    below, the two print statements depend on the outcome of the test in the if statement, as such these
    statements must be enclosed within the pair of curly brace, as shown below..

        if ( 30 > 25 )
        {
             System.out.println(“That is correct”);
             System.out.println();
        }

Again, in this case the conditional expression is evaluated to true, hence, the block of statements is
executed.

In Example 4.1 we used a relational expression for the conditional expression. Logical expressions can
also be used, as we will see in the next example.
Example 4.2

       The ABC Company offers scholarships to individuals who are in need of
       financial assistance. The company advertises the scholarship nation wide.
       Preference however, is given to Florida residents who range from 18 years old
       to 25 years old.

       Write a class called Scholarship that accepts the name, age, and the state in
       which the applicant resides. Include a Boolean instance method called
       checkEligibility that determines a candidate‟s eligibility for a scholarship. The
       class must also provide methods to retrieve the name and age of those
       applicants who are selected.

Analysis
    Name of entity:
        o Scholarship.

       Member variables:
        o name, state (String)
        o age (int).

       Things to be done:
            o Determine eligibility (check the state)
            o Provide method to return whether or not the individual is eligible (true/false)
            o Provide methods to return other relevant information such as name and age

       To determine eligibility status of an applicant, we must form a logical expression using age and
        place of residence as operands. That is:

                 state.equals(“Florida”) && age >= 18 && age <= 25

        Let us lift the restriction from strict equality on the variable state, to one of ignoring the case, by
        using the method equalsIgnoreCase(). If we use this method then it will take care of both
        lowercase and uppercase characters.

   Listing 4.3 shows the definition for the class called Scholarship. The instance method
   checkEligibility(), is central to the class, in that the use of the if statement applies a logical
   expression. This is demonstrated on Line 13. The if statement uses that Boolean expression to
   determine if the individual is eligible for a scholarship. If the result of the test is true, then the Boolean
   variable eligible is assigned the value true, otherwise it is false by default. You should also notice
   that this form of using the if statement has no alternate choice.



   public class Scholarship
   1. {
    2.       String name,state;
    3.       int age;
    4.       boolean eligible;

    5.       public Scholarship(String name, int age, String state)
    6.       {
    7.          this.name = name;
    8.          this.age = age;
    9.          this.state = state;
    10.      }

    11.      public void checkEligibility()
    12.      {
    13.         if (state.equalsIgnoreCase("Florida") && age >= 18 && age <= 25 )
                       eligible = true;
    14.      }

    15.      public boolean isEligible() { return eligible; }
    16.      public String getName() { return name; }
    17.      public int getAge() { return age; }
    18. }

Listing 4.4 Using if to determine a situation.

The class Scholarship simply determines if the individual is eligible for a scholarship. However, it is left to
the test class to determine what information it wants from this class. Suppose we want an output as shown
in Figure 4.5




      Figure 4.5 The desired result from the program.
Let us further assume that we want to use three separate print statements to generate this result. Notice that
this output only accounts for those individuals who get an award. That is, no mention is made of anyone
who does not get an award. This being the case, the test class can call the Boolean method isEligible() in
the class Scholarship to determine who gets an award.

The test class is shown in Listing 4.4. The if statement shown on Line 8 simply uses the Boolean result
returned by the isEligible() method to determine if the three statements that depend on this outcome must
be executed. Once again, notice that this form of using the if statement does not have an alternate choice.
    1. public class TestScholarship
    2. {
    3.    public static void main(String[] arg)
    4.    {
    5.         scholarship s = new scholarship("John Brown", 20, "FLorida");
    6.         s.checkEligibility();
    7.
    8.         if (s.isEligible())
    9.         {
    10.             System.out.println(s.getName() + " is " + s.getAge() + " years old");
    11.             System.out.println("This person gets a scholarship");
    12.             System.out.println("This person is a Floridian");
    13.        }
    14.   }
    15. }

Listing 4.4 Using if to determine who is illegible.



The if .. else Statements
The if .. else statement specifies at least one alternate choice. The general format of this statement is as
follows:

         if (condition1)
                   statement1;
         else if (condition2)
                   statement2;
                       :
                       :
         else if (conditioni )
                   statementi ;
          else
                   statement;

Figure 4.6 shows how the if..else statement works. The diagram illustrates that whichever of the
conditional expressions results in true, the associated statement or block is executed, and the rest of the
statement is skipped. If none of the conditions yields true, then the last block following the last false, is
executed.




                                                               true
                      conditional expression                                  S/block
                          false
                                                              true
                    conditional expression                                 S/block



                          false
                                                             true
                     conditional expression                                 S/block



                        false

                            S/block




Figure 4.6 The if/else construct and how it works.


Example 4.3.

      The ABC Company offers scholarships to individuals who are in need of
      financial assistance. The company advertises the scholarship nation wide.
      Preferences are given according to the following rules:

         Florida residents get 50% of the fund with no age restriction
         Other US residents get 35% of the fund, but must be 18 to 30 years old
         International students get 15% of the fund, but the applicant must be 18 to 25 years old.

      Write a class called Scholarship that accepts the name, age, the place of
      residence, and the amount of money that is to be awarded. Include an instance
      method called checkEligibility, that determines the eligibility of each applicant.
      The class must also provide methods to retrieve each attribute.
      Write a test class that reports on applicants‟ eligibility status, including those
      that are ineligible.

Analysis
    Name of entity
         o Scholarship.
    Possible member variables
         o name, state.(String)
         o age (int)
         o Boolean variable representing an applicant ‘s origin – florida, usa, international
        Things to be done
             o Determine eligibility (check the state)
             o Provide method to return whether or not the individual is eligible (true/false)
             o Provide methods to return any other useful information

In this exercise we need to identify the three categories of applicants: Floridians, US residents who are non-
Floridian, and international applicants.

Note:
        Eligibility for Floridians is based on place of residency alone.
        Eligibility for other US residents is based on place of residence, and also on age.
        Similarly, eligibility for international applicants is based on place of residence, and also on age.

Figure 4.7 shows how the process of checking the eligibility status of each applicant works.



                                                 true
                Florida eligible                                 Process award for Florida


                  false

                                                   true
              USA eligible                                      Process award for USA


                  false

                                                   true
                                                              Process International student award
              International eligible
                           false

                  false



                  Not eligible



Figure 4.7 using multi-way testing to check the eligibility status of applicant


For each of these situations we can build the requisite Boolean expressions. That is:

        The expression for Floridian is: state.equalsIgnoreCase("Florida”)

        For other US citizen::state.equalsIgnoreCase("USA") && age >= 18 && age <= 30

        International students: state.equalsIgnoreCase("International") && age >= 18 && age <=
         25
We will use the if..else construct to implement these alternative expressions. Against this background it is
necessary to maintain the three Boolean variables - florida, usa, international – to store the status of an
applicant. Listing 4.5 shows the class Scholarship.

    1. public class Scholarship
    2. {
    3.    private static final double FL    = 0.5;
    4.    private static final double US    = 0.35;
    5.    private static final double OTHER = 0.15;

    6.       private String name, state;
    7.       private int age;
    8.       private boolean eligible,florida, usa, international;
    9.       private double award, amount;

    10.      public Scholarship(String name, int age, String state, double amount)
    11.      {
    12.          this.name = name;
    13.          this.age = age;
    14.          this.state = state;
    15.          this.amount = amount;
    16.          eligible = true;
    17.      }

    18.      public void checkEligibility()
    19.      {
    20.          if (state.equalsIgnoreCase("Florida"))
    21.          {
    22.                 florida = true;
    23.                 award = amount * FL;
    24.          }
    25.          else if (state.equalsIgnoreCase("USA") && age >= 18 && age <= 30)
    26.          {
    27.                 usa = true;
    28.                 award = amount * US;
    29.          }
    30.          else if (state.equalsIgnoreCase("International") && age >= 18 && age <= 2 5)
    31.          {
    32.                 international = true;
    33.                 award = amount * OTHER;
    34.          }
    35.          else
    36.                 eligible = false;
    37.      }
    38.      public boolean isFloridaEligible() { return florida; }
    39.      public boolean isUsaEligible() { return usa; }
    40.      public boolean isInternationalEligible() { return international; }
    41.      public boolean isEligible() { return eligible; }
    42.      public double getAward() { return award; }
      43.       public String getName() { return name; }
      44.       public int getAge() {return age;}
      45. }

Listing 4.5 Class Scholarship.

There are several things to observe in Listing 4.5, namely:

      1.    The central theme of this class is the use of the if..else statement, which is implemented by the
            method checkEligibility, Lines 18 – 37.

      2.    The use of the if..else statement is a translation of Figure 4.7.

      3.    Line 8 shows the Boolean variables that are used to keep track of the eligibility status of each
            applicant.

      4.    The variable called eligibility is used to track whether or not any applicant was successful. At the
            beginning we assume that every applicant is eligible, so we set this variable to true, in the
            constructor – Line 16. If during the process we find that an applicant is ineligibly, we reset the
            value to false. As seen on Line 36.

      5.    The second and third if..else statement, each implements logical expression, instead of simply a
            relational expression.

      6.     Each if..else statement comprises a block with two statements, hence these statements are placed
            within pairs of curly braces. The last else statement comprises only a single statement. This single
            statement does not require curly.

Listing 4.6 shows a typical test class for the class Scholarship. Notice that after an applicant object has
been created, we must call the checkEligibility method.

1. import java.text.NumberFormat;
2. import java.util.Scanner;

3. class TestScholarship
4. {
5.   public static void main(String[] arg)
6.   {
7.     NumberFormat nf = NumberFormat.getCurrencyInstance();
8.     Scanner read = Scanner.create(System.in);
9.     String name = read.next();
10.    int age = read.nextInt();
11.    String residency = read.next();
12.    int amount = read.nextInt();

13.         Scholarship s = new Scholarship(name, age, residency, amount);

14.         s.checkEligibility();
15.        System.out.println(s.getName() + " is " + s.getAge() + " years old " );

16.        if (!s.isEligible())
17.              System.out.println("Applicant is not eligible for scholarship ");
18.        else
19.        {
20.            if (s.isFloridaEligible())
21.                 System.out.println("is a Floridian");
22.            else if (s.isUsaEligible())
23.                 System.out.println("is a USA student not from Florida");
24.            else
25.                 System.out.println("is an international student");
26.            System.out.println("gets a scholarship of " + nf.format(s.getAward()));
27.        }
28. }
29. }

Listing 4.6 TestScholarship – a typical test class for the class Scholarship.

In generating the report for each applicant, we must identify the candidate by using once again the if..else
statement. In this case however, there is something that is different from the former usage. Inside the first
else statement there is an if..else statement. You may wonder why. If the applicant is not eligible, then the
first print statement is executed. If this is not the case, then the applicant is eligible. This is represented by
the else statement. Since the applicant would be eligible, then we must identify which kind it is. It is against
this background we need the if..else statement within the first else statement.


Pitfalls
If you do not fully understand the if statement, you could write codes that either do not compile, or worst,
codes that compile but give the wrong answer. In this section you will learn about the common types of
mistakes that beginning programmers make, ways by which you can avoid them, and ways you can correct
them, if you should make any of them.


Pitfall I – Misplacing Semi-colon


The if statement must be viewed as one complete thought, for both the single statement and the block of
statements. In the first case, the statement:

           if ( 30 > 25 )
                System.out.println(“That is correct”);

can be written as

           if ( 30 > 25 ) System.out.println(“That is correct”);

Similarly the statement:
         if ( 30 > 25 )
         {
                  System.out.println(“That is correct”);
                  System.out.println();
         }

This means the same as:

         if ( 30 > 25 ) { System.out.println(“That is correct”); System.out.println(); }

The indentation is only used for readability, but nothing else. Sometimes beginning students want to regard
the if part of the statement as separate from the statement/statement block, so they write the code this way:

         if (30 > 200);
                  System.out.println("Wow!!");

This code compiles, but the result is incorrect, since the if statement is followed literally by no statement.
Notice the semi-colon following the if clause. In this situation the print statement will be executed
regardless of the outcome of the conditional expression.


Pitfall II – Separating else with semi-colon
A second type of pitfall occurs when using the if ..else statement. Consider Listing 4.7.



    1. class Pitfall
    2. {
    3.     public static void main(String arg[])
    4.     {
    5.         if (30 > 200);
    6.              System.out.println("Wow!!");
    7.         else
    8.              System.out.println("Ohh!!");
    9.         }
    10. }

    Listing 4.7 Pitfall is using the if ..else construct.

Again if you think of the if as separate for the rest of the statement, and place a semi-colon after the if
clause, you will run into even a worst problem. This time the code will not compile, because the compiler
considers the following segment to be separate from the if the clause:



                         System.out.println("Wow!!");
                  else
                         System.out.println("Ohh!!");
When this happens the compiler complains that the else does not have a corresponding if. Figure 4.8 shows
the actual compilation error message.


              --------------------Configuration: j2sdk1.4.2_03 <Default>-----------
              C:\ Listing4.5\Pitfall.java:7: 'else' without 'if'
                         else
                           ^
              1 error



            Figure 4.8 Error because if ..else statement is incorrectly expressed.


Notice that the caret points to the else, suggesting that something is wrong with the way in which the
statement is written. In addition, the compiler is telling you that on the preceding line, the else clause does
not have an if clause corresponding to it.



Pitfall III – Failing to block statement properly
A third pitfall is failure to enclose a block of statement within curly braces. If a statement were to follow an
if statement, such statement would have been executed regardless of the outcome of the test, since the if
statement itself is a complete thought. For example, consider the following segment of code:

         if ( 30 > 20 )
                  System.out.println(“Yes”);
         System.out.println(“Oh well!”);

In this piece of code there are only two statements, the if statement and the second println statements. The
second print statement will be executed regardless of the outcome of the if statement. If it was meant that
both print statements were to be executed based on the outcome of the if clause, then both of them must be
enclosed within a pair of curly braces.



Pitfall IV – Misusing series of if statements
Beginning programmers often times believe that you can use a series of if statements instead of the if..else
construct, and still get the correct result. For instance, consider Example 4.4.

Example 4.4

      The ABC Company gives wards to its employees for long service to the company.
      The awards are as follows:

      An employee who serves over ten years gets one thousand dollars; anyone
      who serves eight to ten years gets five hundred dollars; and anyone who
      serves less than eight years is not entitled to an award.
      A beginning programmer who is learning about the if statement might be tempted to believe that a
      series of if statements can solve this problem, hence they might write code as shown in Listing 4.8,
      Lines 7 – 9.



    1. public class Pitfall4
    2. {
    3.    public static void main(String[] arg)
    4.    {
    5.         int years = 19;
    6.         float award = 0;

    7.              if (years > 10)
                             award = 1000;
    8.              if (years >= 8)
                             award = 500;
    9.              if (years > 0 )
                             award = 0;
    10.             System.out.println("Your award is " + award);
    11.      }
    12. }

   Listing 4.8 Using series of if statements, instead of using if..else.



Pitfall V – Misrepresenting nested if statements
Another type of mistake is using nested if statements without due care of matching if with else. The
construct of the if statement is:

         if (condition)
              S;

where S is any valid Java statement. But what if S itself is an if..else statement, then the construct would
now look like the if statement shown below:

         if ( condition_1 )
               if ( condition_2 )
                       statement_1;
             else
                      statement_2;

Since the second if statement is a substitute for statement S, then the else belongs to the if in this second if
statement.

If the statement was written as:
             if(condition)
             {
                S1;
             }
             else
                  S2;

If S1 is another if statement, then the entire statement is now interpreted as:

         if ( condition )
         {
                    if ( condition_2 )
                           S;
         }
         else
             S;


Example 4.4

A beginning programmer was asked to use the if statement to determine those students who were
marginally passing a course and those who were definitely failing. The problem definition went this way:

    Any student whose average is more than 70 is passing the course, but those with
    average less than 75 is marginally passing the course; any student with any
    other grade is failing the course.

The programmer wrote the code exactly the way is it given in the narrative. Listing 4.9 shows the code
produced by the programmer, as seen in the method determineStatus(int grade).

    1. class PitFall
    2. {
    3.     public static void main(String[] arg)
    4.     {
    5.         determineStatus(80);
    6.     }}

    7.          static void determineStatus(int grade)
    8.          {
    9.              System.out.println("Your average is " + grade );

    10.             if(grade >70)
    11.                  if (grade < 75)
    12.                       System.out.println("You are marginally passing the course");
    13.                  else
    14.                       System.out.println("You are failing course");
    15.         }
    16. }
    Listing 4.9 Erroneous code produced by programmer.

The programmer knows that he has a grade of 80, so he tested his program with his grade. When he ran the
program with his grade, to his astonishment his program said that he is failing. See Figure 4.9.




    Figure 4.9 Erroneous answer.


Pitfall VI Misusing = and ==
Another common mistake that beginning programmer makes is to use = instead of == when comparing two
items for equality. Recall that the equal symbol ( = ) is used to assign values, but the double equal symbol (
== ) is used as a relational operator to form a Boolean expression.

For instance, consider the following code:


         static void determineStatus(int grade)
         {
                 if (grade = 80)
                         System.out.println("The values are equal");
         }

Notice that the statement grade = 80 is assigning the value 80 to the variable grade and not a relational
expression between grade and 80. Hence, the compiler flags this usage as a syntax error. Figure 4.10 shows
the actual compilation error message.


           C:\ chapter4\Examples\Example4.16\PitFall.java:10: incompatible types
           found : int
           required: boolean
                           if (grade = 80)
                                ^
           1 error

          Figure 4.10 relational expression required and not an assignment statement.
In this error message the compiler tells us that the if statement is not constructed properly. The third line
specifies that a Boolean expression is required, not an assignment statement.
Rules Governing the if Statement



              The if statement requires Boolean expression.

              The Boolean expression must be placed within a pair of parentheses.

              A block of statements must be enclosed within curly braces.

              The statement(s) can be any valid Java statement including conditional statement also.

              When if statements are nested without priority, the else is associated with the inner if.

              To prioritize an else clause, you must use curly braces.
The switch Statement

The switch statement is an alternate method for multi-way selection. The switch statement is a special case
of the if..else statement in the sense that it can only test some integral values. This means that the statement
cannot test floating-point values or string values. The only values that the switch statement can test are
byte, short, int, and char. It does not accept long. The general format of the switch statement is:

         switch (selectionVariable)
         {
                 case value1:
                          statement1;
                 break;
                 case value2:
                          statement2;
                 break;
                    :
                    :
                 case valuei;
                      statementi;
                 break;
                 default:
                          statement;
                 break;
         }

With the introduction of the switch statement, are four new reserved words: switch, case, break, and
default. Where:
    1. The switch expression contains the integral value that is to be matched with the case label values.

    2.   The case statement provides entry to the statement or set of statements that are to be executed if a
         match is made. The case label must be a constant. Each case label must be unique.

    3.   The default statement specifies what must be done if no match is made. It is optional, and may be
         placed anywhere within the scope of the switch statement.

    4.   The break statement terminates the switch statement.

Example 4.5

      Design a class called StudentStatus that displays a student‟s status in a
      university, based on the following codes:
       Code         Student status
        1           Freshman
        2           Sophomore
        3           Junior
        4           Senior
The class accepts a code number and returns the status of the individual.

Analysis

          Name of class
              o StudentStatus
          Instance variables needed
              o The code (int)
              o String s that holds the value for the status to be displayed.
          Instance method
              o determineStatus that uses the switch statement to determine the status..
              o toString method to return the status of the individual.

In order to determine the status of each student, we can start by first making a diagram to depict the
situation. See Figure 4.11.



                 code = ..




                    code == 1                            Freshman




                     code == 2                           Sophomore




                    code == 3                              Junior




                    code == 4                              Senior




                     Not an undergraduate




        Figure 4.11 Diagram depicting the solution to selecting the right option
 Listing 4.8 shows the solution to the student status problem. This is in part a direct translation of Figure
 4.11.

    1     public class StudentStatus
    2     {
    3        String s;
    4        int code;

    5          public StudentStatus(int code)
    6          {
    7            this.code = code;
    8            s = "";
    9          }

    10         public void determineStatus()
    11         {
    12           switch(code)
    13           {
    14           case 1:
    15                s = "Freshman";
    16           break;
    17           case 2:
    18                s = "Sophomore";
    19           break;
    20           case 3:
    21                s = "Junior";
    22           break;
    23           case 4:
    24                s = "Senior";
    25           break;
    26           default:
    27                s = "Not an undegradute";
    28           break;
    29           }
    30         }

    31         public String toString(){ return s; }
    32    }

Listing 4.8 Using the switch statement

The central theme to this exercise is the use of the switch statement. The method determineStatus()
implements this concept. Line 12 shows how the keyword switch is applied; also, it shows how the selector
variable, code, is applied. The body of the switch is enclosed within a pair of curly brace, as shown on Line
11 and Line 29. Notice also, that each case has a unique label – 1, 2, 3, 4 – in this example. The default
statement which spans Line 26 thru 28 takes care of any code value that is neither 1, 2, 3, nor 4.



The switch statement can represent logical-OR. The construct representing logical-OR has the following
form:

         switch(selectorVariable)
         {
                 case value1:
                 case value2:
                         S;
                 break;
                  :
                  :
         }

The case statements are interpreted as follow:

If the value in the variable called selectorVariable matches case label value1 or if it matches case label
matches case label value1 or if it matches case label value2, execute statement S, then execute statement
S.

Example 4.6

         An internet service provider has three subscription packages for its
         customers. The packages are as follows:

         Package A: For $9.95 per month, 50 hours of access are provided free.
         Additional hours are charged at $0.12 cents per hour.

         Package B: For $14.95 per month, 100 hours of access are provided free.
         Additional hours are charged at $0.07 hours.

         Package C: For $39.95 per month unlimited access is provided.


         Design a class called InternetServiceProvider that accepts a character
         and an integer value, where the character represents the package type
         and the integer value represents the number of hours used. Include a
         method that determines the package type and calculate each customer‟s
         monthly bill. Note – the number of hours used in a month cannot exceed
         720.

         Design a test class to implement the class InternetServiceProvider.

The design of this class follows similar pattern to the previous example. As a design consideration, identify
the following:
         Those values that can be regarded as constants.
         Separate methods that test for extraneous situations, for example, design methods to test
          specifically any value that could be negative, and any value that could exceed the allowable
          number of hours in an average thirty day month.
         A method that is dedicated to determine he charges for each customer. This method uses the
          switch statement exclusively for the purpose of determining the charges. When we treat the
          solution this way, the overall solution is not cluttered with extraneous ideas.

Listing 4.9 shows the solution for the class InternetServiceProvider.

    1. import java.text.NumberFormat;
    1. public class InternetServiceProvider
    2. {
    3.    static double PACKAGE_A = 9.95;
    4.    static double PACKAGE_B = 14.95;
    5.    static double PACKAGE_C = 39.95;
    6.    static int MAX_HOURS = 720;
    7.    int          hours;
    8.    char         pakage;
    9.    double       charges;
    10.   String       message;

    11.       public InternetServiceProvider(char p, int hours)
    12.       {
    13.          this.hours = hours;
    14.          pakage = p;
    15.       }

    16.       public boolean isGreaterThanZero()
    17.       {
    18.           return hours > 0;
    19.       }
    20.       public Boolean exceed720()
    21.       {
    22.          return hours > MAX_HOURS;
    23.       }

    24.       public void calculateCharges()
    25.       {
    26.          switch(pakage)
    27.          {
    28.               case 'a':
    29.                case 'A':
    30.                   message = "PACKAGE A";
    31.                   charges = PACKAGE_A;
    32.                    if (minutes > 50) charges = charges + (hours - 50) * 0.12;
    33.                break;
    34.                case 'b':
    35.                case 'B':
    36.                    message = "PACKAGE B";
    37.                    charges = PACKAGE_B;
    38.                    if (minutes > 100) charges = charges + (hours - 100) * 0.07;
    39.                break;
    40.                case 'c':
    41.                case 'C':
    42.                    message = "PACKAGE C";
    43.                    charges = PACKAGE_C;
    44.                break;
    45.                default:
    46.                    message = "No such PACKAGE";
    47.                    charges = 0;
    48.                break;
    49.           }
    50.      }

    51.      public String toString()
    52.      {
    53.           NumberFormat df = NumberFormat.getCurrencyInstance();
    54.           return "Your package is " + message +
                          "\nYour charge for this month is " + df.format(charges);
    55.      }
    56. }

    Listing 4.9 Using the switch statement in the form of logical-OR.

The use of the switch statement in this exercise places emphasis on the case statement. Since someone
could input uppercase letters as well as lower case letters, provision is made for both situations by using the
case statement as a logical-OR. For example, see Lines 23 and 24, or Line 29.

Listing 4.10 is a typical test class for the class InternetServiceProvider. It further makes us of the
if..else statement in determining a customer’s bill. Notice the use of the nested if concept.



    1. class TestInternetService
    2. {
    3.     public static void main(String[] arg)
    4.     {
    5.         InternetServiceProvider t = new InternetServiceProvider('b', 500);

    6.            if (t.isGreaterThanZero())
    7.            {
    8.                     if (t.exceed720 ())
    9.                           System.out.println("The number of hours given exceeds the allowable
         limit");
    10.                    else
    11.                    {
    12.                           t.calculateCharges();
    13.                           System.out.println(t);
    14.                    }
    15.             }
    16.             else
    17.                    System.out.println("Error: cannot calculate charges");
    18.      }
    19. }

Listing 4.10 Using nested if to determine customer’s bill.



The switch statement can be used to represent logical-AND, as seen in the following construct:

         switch(selectorVariable)
         {
                 case value1:
                 case value2:
                         :
                 switch(selectorVariable)
                 {
                         case value1:
                                 statement;
                                 :
                         break;
                         :
                 }
                 break;
                   :
                   :
         }

When we use the switch statement as logical-AND this usage is regarded as nesting the switch statements.
That is, a switch statement within another switch statement. The following example shown in Listing 4.11,
uses the switch statement to determine what kind of day of the week it is. Notice the use of the logical-OR
especially Lines 9 – 12. The switch statement is used again on Line 14. This time its use indicates a
logical-AND operation. This means the first switch, shown on Line 7, identifies the kind of days in
general, but the second switch, Line 14, identifies specific kind of days.



    1. import javax.swing.JOptionPane;
    2. public class TheDays
    3. {
    4.    public static void main(String arg[])
    5.    {
    6.         int day = Integer.parseInt(JOptionPane.showInputDialog("Get an integer 1 -
          7"));

    7.            switch (day)
    8.            {
    9.                case 1:
    10.               case 2:
    11.               case 3:
    12.               case 4:
    13.                   System.out.println("This is a school day");
    14.                   switch(day)
    15.                   {
    16.                        case 1:
    17.                            System.out.println("This is Monday day");
    18.                        break;
    19.                        case 3:
    20.                            System.out.println("This is Wednesday, lab day");
    21.                        break;
    22.                        default:
    23.                            System.out.println("Just another school day");
    24.                        break;
    25.                   }
    26.               break;
    27.               case 5:
    28.                   System.out.println("Soon it will be weekend");
    29.               break;
    30.               case 6:
    31.               case 7:
    32.                   System.out.println("Weekend is here!!!");
    33.               break;
    34.               default:
    35.                   System.out.println("Not a day of the week");
    36.               break;
    37.           }
    38.       }
    39. }

    Listing 4.11 using the switch statement as logical-AND and logical-OR.

Notice that the second switch is nested within the first switch statement. See Lines 14 – 25, the nested
switch.
Pitfalls


Very often beginning programmers make several kinds of errors when learning the switch statement. Like
the if and if..else they make syntax errors as well as logic errors.



Pitfall I – Forgetting the parentheses
One type of errors that students make, is forgetting the parentheses in the switch clause. As a result they
write codes such as the following:

           switch day
           {
                case 1:
                    System.out.println("This is a school day");
                break;
                default:
                break;
           }

In this example, notice that the parentheses around the selector variable – day – is missing.


Pitfall II – Forgetting the braces.
A second form of error is forgetting the opening braces following the keyword switch. As a result the
practicing programmer writes code such as the following:

           switch (day)
             case 1:
                 System.out.println("This is a school day");
             break;
             default:

               break;


Pitfall III – Forgetting the break keyword
Although forgetting the break statement does not constitute syntax error, it represents logic error. Failure to
place it when it is required can lead to devastating results.

Example 4.7

           Real Estate Licensing School Inc offers four kinds of lessons to participants
           who want to be licensed to do business in a particular state. The school
           charges a non-refundable registration fee of $50.00 for each applicant. The
           fee table for each kind of class is as follows:
             Life Insurance                  $250.00
             Health Insurance                $150.00
             Mortgage Brokerage              $350.00
             Appraisal                       $300.00

          Requirement – write a program to display the course that the applicant
          registers for, and the total cost of the course.

Let us assume that two people worked on the program – one writes the test class and the other writes the
class that determines the course the applicant registers for, and the total amount of money due.

Programmer A writes a menu driven interface as shown in Listing 4.13.

    1. import javax.swing.JOptionPane;

    2. public class TestCertification
    3. {
    4.    public static void main(String[] arg)
    5.    {
    6.           String s = JOptionPane.showInputDialog("1. Life insurance\n2. Health
                         insurance\n" +"3. Mortgage\n4. Appraisal\nMake selection");
    7.         int x = Integer.parseInt(s);

    8.            Certification c = new Certification(x);
    9.            c.getCost();
    10.           System.out.println(c);
    11.      }
    12. }

Listing 4.13 Menu driven interface to the class Certification.

Programmer B is given the task of writing the class that carries out the checking and the calculations.
Programmer B comes up with codes as shown in Listing 4.14.

    1. public class Certification
    2. {
    3.    int code;
    4.    double cost;
    5.    String s;
    6.    static final double LIFE_INSURANCE                             = 250,
                                HEALTH_INSURANCE                         = 150,
                                MORTGAGE                                 = 350,
                                APPRAISAL                                = 300,
                                REGISTRATION                             = 50;

    7.       public Certification(int code)
    8.       {
    9.          this.code = code;
    10.         cost = REGISTRATION;
    11.         s = "";
    12.      }

    13.      public void getCost()
    14.       {
    15.           switch(code)
    16.           {
    17.               case 1:
    18.                   cost = cost + LIFE_INSURANCE;
    19.                   s = s + "Life insurance ";
    20.               case 2:
    21.                   cost = cost + HEALTH_INSURANCE;
    22.                   s = s + "Health insurance ";
    23.               case 3:
    24.                   cost = cost + MORTGAGE;
    25.                   s = s + "Mortgage ";
    26.               case 4:
    27.                   cost = cost + APPRAISAL;
    28.                   s = s + "Appraisal";
    29.               break;
    30.               default:
    31.                   s = “No such course is offered”;
    32.                   cost = 0;
    33.               break;
    34.           }

    35.       }
    36.       public String toString() { return cost + " " + s;   }
    37. }

    Listing 4.14 the class Certification.

When the program is executed, the input dialog window shown in Figure 4.12 appears. The option is
typed, in this case option 1. The program proceeds to carrying out the process. To the dismay of
programmer B, the output was not what was expected. See Figure 4.13.




            Figure 4.12 the input dialog window.
          Figure 4.13 the incorrect result from the switch statement of the program.



Rules Governing the Switch Statement



                    The control expression or selector variable that follows the keyword
                     switch must be an integer or an integer equivalence, except the data
                     type long.
                    The expression, called case-label, that follows the keyword case must
                     be a constant, and not a variable.
                    The case-label must be unique. That is, no two case-labels must ever
                     evaluate to be the same value.
                    There can be no more than one default in a given switch statement



                                             Exercises 4b

   1.   Pitfall I thru III show common errors make by beginning programmers. Re-write each pitfall so
        that each produces the desired result.

   2.   Given the following code:
         char m = „a‟;
         switch(m)
         {
               case „a‟:
                     System.out.println(“a”);
               break;
               default:
                     System.out.println(“default”);
               break;
         }

        What will happen when you attempt to compile and execute this code?
           (a) The code will not compile because the switch statement does not have a legal value.
           (b) The code will compile and run, but nothing will be printed on the screen.
           (c) The code will compile and run, and the letter a will be outputted on the screen.
           (d) The code will compile and run, and the letter m will be outputted on the screen
           (e) The code will compile and run, and the word default will be outputted on the
                screen
3.    Study the following segment of code.

       1.    int j = 5;
       2.    switch(j)
       3.    {
       4.         case 3 + 2:
       5.             System.out.println(“The value is 5”);
       6.         break;
       7.         default:
       8.             System.out.println(“The value is undeterminedj”);
       9.         break;
       10.        case 4:
       11.            System.out.println(“The value is j”);
       12.        break;
       13.   }

What statements are true about this segment of code?

     (a)   The code is illegal because the arithmetic expression at Line 4.
     (b)   The code will compile and run, and The value is 5 is printed on the screen.
     (c)   The code will compile and run, and The value is undetermined is printed on the screen.
     (d)   The code will compile and run, and The value is j is printed on the screen
     (e)   The default statement should come last in the series of case statement.

				
DOCUMENT INFO