Unit 2

Selection Structures & String Manipulation

Key Concepts

bullet

Computer program instructions are executed in sequence.

bullet

Selection structures allow the program to select which instructions will be executed based upon defined conditions.

bullet

If statements are a common form of selection structure in most programming languages.

if ... else

We use selection many times every day as we make decisions.  For example, if you have access to a car that you share with your family and drive to school when the car is available, you might say:

if the car is available
    drive to school

In these two statements, the keyword "if" indicates the condition is "the car is available."  The action is "drive to school."  This form of selection is called an if statement in programming.  The obvious question is what will happen if the car is not available.  In this case an alternate action should be stated.

if the car is available
    drive to school
else
    take public transit to school

The word else indicates the "take public transit" is the alternate action that will take place if the condition is NOT true.  Only one condition can be true.  The else portion of an if ... else statement is also known as the default condition since it ensures that some action will occur.

else ... if

Sometimes there are more than two possible actions.  For example, if the car was not available, and public transit was not running, the mode of transportation might be taking a bicycle.  If the bicycle is not available you may choose to get to school using a skateboard. (Please don't borrow it from your younger brother or sister without asking.)  You can add as many else if statements to the if statement as you have possibilities available but remember that only one action can occur.  The first condition that is true will have its action execute. 

if the car is available
    drive to school
else if public transit is running
    take public transit to school
else if the bicycle is available
    take the bicycled to school
else if the skateboard is available
    take the skateboard to school
else
    walk to school

Again, the "else" statement, the default condition, ensures that you will go to school regardless.  It is not necessary that an "if" statement have an "else if" component.  In the case of a singular if statement, if the condition is not true, the program will simply proceed to the next line of code and no action will occur as a result of the if statement.  It is also possible to have "if" and "else if" statement without having an else condition.  If none of the "if" or "else if" statements have true conditions, no action will occur and the program will simply execute the next line of code after the if structure.

if Statements in Java

If the cost of an adult movie ticket is $14.50 and the cost of a student's ticket is $5.75, the if statement in Java would be stated as: (assume that int age and double ticketPrice have previously been declared)

if (age < 16) {
    ticketPrice = 5.75;
}
else {
    ticketPrice = 14.50;
}

Notes:

bullet

The keywords if and else must be lower case.

bullet

A line that contains a key word does not end with a semi-colon.

bullet

The condition is in parentheses (age < 16)

bullet

By convention the action statements should be indented.

bullet

Each set of actions is contained in braces.  The braces may be omitted if there is only one action but it is good practice to include them.

else if in Java

If there are more than two possible actions, the key word else is used in Java.  If a senior's ticket is $4.50 and a child's ticket is $3.00 the above statement would look like this to include the additional parameters. (assume seniors are over 65 years of age and children are under 10)

if (age > 65) {
    ticketPrice = 4.50;
}
else if (age < 10) {
    ticketPrice = 3.00;
}
else if ( age < 16) {
    ticketPrice = 5.75;
}
else {
    ticketPrice = 14.50;
}

The order of the else if statement is very important.  In the previous example if the two "else if" statements were reversed a child would be charged $5.75 rather than $3.00.

if without else

In some cases, there is an action to carry out if a condition is true and nothing to do if the condition is not met.  If a discount of 25% is applied to all purchases over $200, the statements that would reflect this are:

double discount = 0;
if (purchase > 200.00) {
    discount = purchase * .25;
    purchase -=discount;
}

The assumption is that in the case that the purchase is less than or equal to $200.00, no discount is applied.  Also note that in the above section of code the second statement would not be carried out if the brace brackets were not used in the if statement.

if ... else if ... else Sample Program

Situation:

A video game allows 1 free game for a point total of over 10,000 points, 3 free games for a total of over 20,000 points and 5 free games for a score of over 25,000 points.  The following is a program which will calculate the total number of free games the user is entitled to.

Solution:

/* The IfSample Program
*  Programmed by Mr. J. Augustine, February 2004
*  This program will accept as input the score from a video game and output
*  the number of free games a user will get based on the value input. It
*  allows 1 free game for a score of over 10,000 points, 3 free games for a
*  score of over 20,000 points, and 5 free games for a score of over 25,000
*  points. It is a simple demonstration of the if construct. */

import java.io.*;
import ReadLib;

public class IfSample1 {
    public static void main (String [ ] args) {
        /*The main method will ask for input then send the results to the
        * calcFreeGames method. The results of the calculation are then
        * output to the screen.*/

        int points;

        //user is required to enter the number of points scored
        System.out.print("Enter the number of points that were achieved. ");
        //call the ReadLib class to read the input from the keyboard
        points = ReadLib.readInt();
        //send the results to the calcFreeGames method and put the calculation
        //into the integer freeGames
        int freeGames = calcFreeGames(points);
        //output the results to the screen
        System.out.println("The number of free games is " + freeGames);
    }//end main method

    public static int calcFreeGames(int points){
        //this method calculates the number of free games using an if construct
        int freeGames = 0;

        if (points > 25000)
            freeGames = 5;
        else if (points > 20000)
            freeGames = 3;
        else if (points > 10000)
            freeGames = 1;

        return freeGames;
    }//end calcFreeGames
}//end class IfSample1

Updated Read Class (ReadLib)

The ReadNum class read only int and double types from the keyboard.  The ReadLib class adds boolean, char, and String.  Inclusion of all five types means that a BufferedReader object does not have to be included in every class you write.  The following is the code for ReadLib, copy it and add it to your library of personally developed classes.

/* The ReadLib Class
* Programmed by Mr. J. Augustine, February 2004
* This is a library class of read routines all based upon pressing
* the enter key. Methods fro reading int, double, boolean, char,
* and String types are provided. */

import java.io.*;                         // allows us to use the computer's input and output
import java.util.*;                       // import all java utilities that are necessary to
                                                   // the program. Only those that are necessary will
                                                  // be imported.

public class ReadLib  {
    // The tokenizer is used to get the first item typed on a line, used with the
    // readInt(), readDouble(), and readBoolean() methods.
    static private StringTokenizer stok;

    // The BufferedReader opens the connection to the keyboard
    static private BufferedReader br = new BufferedReader (new InputStreamReader
                                                                        (System.in));

    public static int readInt(){
        // Uses a Tokenizer and Integer wrapper class to get a true int value
        int i;

        try {
            String str = br.readLine();
            StringTokenizer stok = new StringTokenizer (str);
            i = new Integer (stok.nextToken()).intValue();
        } // end try statement

        catch (IOException ex) {         // possible connection failure
            System.out.println(ex);
            i=0;
        }  // end catch

        catch (NumberFormatException nfe) {        // invalid keyboard entry
            System.out.println("Warning: a non-numeric value was entered.");
            System.out.println("Your variable has been given a value of 0.");
            i = 0;
        }  // end catch

        return i;
    }  //end readInt method

    public static double readDouble() {
        // uses a Tokenizer and Double wrapper class to get a true double value.
        double d = 0;

        try {
            String str = br.readLine();
            StringTokenizer stok = new StringTokenizer (str);
            d = new Double (stok.nextToken()).doubleValue();
        }  //end try statement

        catch (IOException io) {   // possible connection failure
            System.out.println(io);
            d=0.00;
        }  // end catch

        catch (NumberFormatException nfe) {   // invalid keyboard entry
            System.out.println("Warning: a non-numeric value was entered.");
            System.out.println("Your variable has been given a value of 0.00");
            d = 0.00;
        }  // end catch

        return d;
    }  // end readDouble method

    public static boolean readBoolean () {
        // reads a boolean value and looks for true or false
        boolean result = false; //assumes false as the default condition

        try {
            String str = br.readLine();
            StringTokenizer stok = new StringTokenizer (str);
            String answer = stok.nextToken();
            
            if (answer.equals ("true"))  {         // valid true entry
                result = true;
            }  //end if
            else {
                if (!answer.equals("false"))     //invalid entry
                    System.out.println("An invalid entry was made, false is assumed.");
                result = false;
            }  //end else
        }  //end try statement

        catch (IOException io) {
            System.out.println(io);
        }  //end catch statement

        return result;
    }  //end readBoolean method

    public static char readChar () {
        //this method will read in a single character from the keyboard
        char oneChar = ' ';

        try {
            String str = br.readLine();
            oneChar = str.charAt(0);     //oneChar is the first character of keyboard entry
        }  //end try statement

        catch (IOException io){         //connection error
            System.out.println(io);
        }  //end catch

        catch (StringIndexOutOfBoundsException se){
            //user pressed the enter key only, no character was entered
            System.out.println("There was no character entered, a blank is assumed.");
        }  //end catch

        return oneChar;
    }  //end readChar method

    public static String readString () {
        //this method will read a string input from the keyboard
        String str = "";

        try {
            str = br.readLine();         //returns null if no characters are typed
        }  //end try statement

        catch (IOException io){
            System.out.println(io);
        }//end catch

        return str;
    }  //end readString method
}     //end ReadLib class

Time to Practice

Now it's your turn.  Write a program called TheBoxer, which uses the ReadLib class to classify the weights of boxers as they approach the ring.  The user should be able to enter the weight of a boxes and the program will announce whether the boxer is classified as a lightweight (under 75 kg.), a middleweight (between 76 kg. and 90 kg.) or a heavyweight (over 90 kg.)

Thinking Through if Structures

To use an if structure correctly we must both follow the correct syntax and set the structure up correctly such that it does what is requested.

If you were writing a program that converts numeric grades to letter grades based on the criteria of:

A covers 80 to 100
B is for grades from 70 to 79
C is for grades from 60 to 69
D is for grades from 50 to 59
F is for grades less than 50

A sample class that converts numeric grades to letter grades is:

/* The LetterGrade Program
* Programmed by Mr. J. Augustine, Janurary. 2004
* This program converts a numeric grade to a letter grade but
* contains a deliberate logic error.*/

import ReadLib;

public class LetterGrade {
    public static void main (String [ ] args) {
        char letter;

        System.out.print("Enter a numeric grade: ");
        int grade = ReadLib.readInt();

        // The following if structure should determine which
        // letter grade to assign, but it has a logic error
        if (grade > 49)
            letter = 'D';
        else if (grade > 59)
            letter = 'C';
        else if (grade > 69)
            letter = 'B';
        else if (grade > 79)
            letter = 'A';
        else
            letter = 'F';

        // Output to the screen
        System.out.println("The letter grade for numeric grade " +
                        grade + " is " + letter);
    }//end main method
}//end LetterGrade class

If you run this program you will see that there are only two possible outputs, F and D no matter what marks are entered.  The first if (grade > 49) is satisfied by all passing marks and will assign a D to all passing grades.  The same conditions but in a different sequence will solve the problem.  Make the following changes and run the program.

if (grade > 79)
    letter = 'A';
else if (grade > 69)
    letter = 'B';
else if (grade > 59)
    letter = 'C';
else if (grade > 49)
    letter = 'D';
else
    letter = 'F';

By starting with the letter A, only those that are above 79 will fulfill the first condition, so all the conditions will be considered.

 

Compound if Statements

A compound if statement uses && (and) or || (or) to join two or more conditions.  The following program calculates the cost of a movie ticket where there are four possibilities.  The cost of a (M)atinee for a (C)hild is 4.50, the cost of and (E)vening ticket for a (C)hild is 5.50.  The cost of a (M)atinee for an (A)dult is 8.00, the cost of an (E)vening ticket for an (A)dult is 12.50.

Given inputs for time (M or E) and type (C or A) the following method would calculate the cost:

public static double calcTicketCost (char showTime, char showType) {

double ticketCost = 0;
if (showTime == 'M' && showType =='C')
    ticketCost = 4.50;
if (showTime == 'E' && showType == 'C')
    ticketCost = 5.50;
if (showTime == 'M' && showType =='A')
    ticketCost = 8.00;
if (showTime == 'E' && showType == 'A')
    ticketCost = 12.50;

return ticketCost;

}  // end calcTicketCost

Nested if Statements

The above program could also be written with nested if statements.  Given the same input parameters, the nested if statements would read as follows:

public static double calcTicketCost (char showTime, char showType) {

double ticketCost = 0;
if (showTime == 'M') {
    if (showType == 'C')
        ticketCost = 4.50;
    else if (showType == 'A')
        ticketCost = 8.00;
}
else if (showTime == 'E') {
    if (showType == 'C')
        ticketCost = 5.50;
    else if (showType == 'A')
        ticketCost = 12.50;
}
return ticketCost;

}  // end calcTicketCost

 

Comparing Strings

The equality operator for numbers in Java is made up of two equal signs.  If you are testing to see if a person's age is 18, the statement would be:

if (age == 18)

Strings can sometimes be compared using the == operator depending on how and where the strings were created but it is not reliable as there are times when it will not work.  The reason has to do with how Java stores string information.  Java does a character by character comparison of strings.  If you wish to check to see if a string variable name is equal to "John" then the Java statement would be:

if (name.equals ("John"))

Other Valuable String Methods

The String class contains methods that help the user to manipulate and test strings.  The following program will illustrate several methods which test and modify a string literal.

/* The StringProperties Program
* Programmed by Mr. J. Augustine, February 2004
* This program gives examples of a variety of methods in the string
* class which can be used to manipulate string literals.*/

public class StringProperties {
    public static void main (String [ ] args) {
        String text = "There is nothing either good or bad, but thinking makes it so.";
        System.out.println("Text: " + text);
        System.out.println("The length of the string is: " + text.length());
        System.out.println("The character at position 17 is: " + text.charAt(17));
        System.out.println("The substring from position 24 to 28 is: " +
                                            text.substring(24,28));
        System.out.println("The location of letter b is at position: " +
                                            text.indexOf('b'));
        System.out.println("The first letter of good occurs at position: " +
                                            text.indexOf("good"));
        System.out.println("The text in upper case is: " + text.toUpperCase());
        System.out.println("The text in lower case is: " + text.toLowerCase());
    }//end main method
}//end StringProperties class

The output is:

Text: There is nothing either good or bad, but thinking makes it so.
The length of the string is: 62
The character at position 17 is: e
The substring from position 24 to 28 is: good
The location of letter b is at position: 32
The first letter of good occurs at position: 24
The text in upper case is: THERE IS NOTHING EITHER GOOD OR BAD, BUT THINKING MAKES IT SO.
The text in lower case is: there is nothing either good or bad, but thinking makes it so.

Step - By - Step

bullet

text is the string literal

bullet

text.length( ) is a method in the String class.  In this case, the string has 62 characters including blanks and the period.

bullet

text.charAt(17) is a method to return the character in the 17th position of the string literal.  Since strings are treated as arrays, index numbering begins at 0.

bullet

text.substring(24,28) is a method to return the substring from position 24 up to but not including position 28.  The length of the substring is 28-24 or 4 letters.

bullet

text.indexOf('b') is a method to return the position of the first instance of the letter 'b'.

bullet

text.indexOf("good") is a method to return the position of the first letter of the substring "good".

bullet

text.toUpperCase( ) is a method to return a copy of the string entirely in uppercase letters.

bullet

text.toLowerCase ( ) is a method to return a copy of the string entirely in lowercase letters.

(String [ ] args) is the array through which the Java Virtual Machine passes information to the application.  args is any user-defined variable name.

Hosted by www.Geocities.ws

1