Google
 
Site navigation: [ Home | Theory | Java | Moodle courses | Resource wiki | About ]

Selection

Selection is also known as branching .

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Internal storage of real numbers is covered in the HL part of the course (Topic 4)

 

 

 

 

 

 

 

 

In expressions which contain mixed and and or operators, the and takes precedence over the or (the and is done first).

 



 

LInk to the quiz page for an interactive quiz on selection statements.

 

 

 

 

 

 

On this page: [ simple selection | conditions | multiple conditions | " nesting " ]

                    [ if else chains | readability | switch | exercises ]

Simple Selection

Selection in a programming language means choosing between alternative courses of action (statements or blocks of statements). Most languages use a construct similar to Java, in general we have:

    if ( condition )
   {
     java statement(s);
   }

Any java statements inside the curly brackets (called braces) are executed if, and only if, the ( condition ) is true. The condition is said to be a boolean condition.

If there is only one statement then there is no need for the braces at all:

  if (height > 2.1)
     somewhere.setText("You are tall");

However, since they improve readability we will always use braces in our examples. Issues of readability are highlighted later.

The if statement may be followed by an else part; this is done if the condition is false:

  if (age > 18)
   {
     somewhere.setText("You are allowed to vote");
   }
   else
   {
     somewhere.setText("You are not yet allowed to vote ");
   }

back to top

Conditions

The most frequently used arithmetic conditions are:

Symbol

Example

Meaning

==

x == 2

True, if x is equal to 2 (false otherwise)

!=

x != 2

True if x is not equal to 2

>

x > 2.1

True if x is greater than 2.1

<

x < 2.1

True if x is less than 2.1

>=

x >= 53

True if x is greater than or equal to

<=

x <= 34

True if x is less than or equal to

Points to remember:

Do not use == or != with real numbers (doubles and floats) since these are not stored precisely in the computer. A real value may appear to be exactly 2.1 but may be stored as 2.099999999999999 internally , for example).

Do not use != and == with String values, use the String method equals: name.equals("Fred") or !(name.equals("Fred")) for example.

You can also use selection statements with characters:

    if (ch == 'y')
   {
     somewhere.setText("You chose \"yes\"");
   }

This example also shows how to put a quote inside a String literal (use the escape character \).

back to top

Multiple conditions

The conditions can be combined with logical and (&&) and or (||) symbols, for example:

  if ( (ch == 'y') || (ch == 'Y') )
   {
     somewhere.setText("You chose \"yes\"");
   }

The condition is true whethere the character ch was a small y (lowercase) or a big one (uppercase). Looked at another way the condition is true if either one is true (or both are).

  if ( (age >=13) && (age <= 19) )
   {
     somewhere.setText("You are a teenager");
   }

The condition is true if both conditions are true, otherwise false. The and (&&) condition is done before the or (||) if brackets are not used:

back to top

if else chains

These are very useful when a numer of alternative choices need to be made (for example user menus). A chain consists of a number of different if statements, only one of which can be true. There is an optional last else which catches any cases not otherwise dealt with.

For example, suppose we collect a user input and we are expecting p, m or c to be input ( complete Applet ):

if (choice.equals("p"))
{
   answer = "But just a soft drink for me, thanks!";
}
else if (choice.equals("m"))
{
   answer = "What shall we watch?";
}
else if (choice.equals("c"))
{
   answer = "OK, I will have a cup of tea...";
}
else
{
   answer = "I don't know where that is";
}

back to top

"Nested " if statements

Control statements (if is a control statement because it controls where the program will go next) can be put one inside another:

if (x == y)
{
   then do this
   if (b != c)
   {
      now do this
   }
   else
   {
      otherwise this
   }
}

back to top

Readability

Remember that you may see if statements without braces in other people's code:

int x = 9;
int y = 0;
int z = 3;
char c = 'x';

if (x == 9)
   if (y < 3)
     if (c != 'x')
       answer = "flip";
     else
       if (z >= 3)
         answer = "flop";
       else
         answer = "fly";

What's the value of answer?

flip, flop or fly? Turn to the quiz page to find out if you are right!

back to top

switch statement

The Java language includes a special statement for multiple choice called a switch, it has its uses but we won't do a lot with it on this course; you may come across it in other examples of code. It can replace an if else chain that uses primitive types like char or int.

For example, if the WhereToday Applet had used a char, we could do something like this:

char choice = name.getText().charAt(0);
String answer = "";

switch(choice) // leaving out the break statement is a common error
{
   case 'p' : case 'P' :
     answer = "But just a soft drink for me, thanks!";
     break;
   case 'm' : case 'M' :
     answer = "What shall we watch?";
     break;
   case 'c' : case 'C' :
     answer = "OK, I will have a cup of tea...";
     break;
   default :
     answer = "I don't know where that is";
}

Some programmers like the switch, some don't. The main differences between switch and an if else chain are:

  1. switch requires primitives like int, short, long, char
  2. switch requires break statements to drop out of the current case

Sometimes the break is left out on purpose (more often by accident), this is known as drop-through execution. Notice that the charAt(0) won't work if the user doesn't type in anything at all! You could test for that separately as part of an if else chain but not with switch:

if (choice.length() == 0)

for example. Just for the sake of interest, here is the WhereToday example using a switch statement.

back to top

Before attempting the exercises you might like to look at an example Applet using selection - the AddSub Applet .

Exercises

In addition to those mentioned in the text :-)

CD Store
At a certain store they sell blank CD's with the following discounts:

  • 10% for 120 or more
  • 5% for 50 or more
  • 1% for 15 or more
  • no discount for 14 or less

Write an Applet that given a number of discs bought can output the correct discount. The SimpleEventApplet ( PressMe ) makes a good framework.

How Old am I?
You don't really want to know. Write an Applet that takes two numbers, the year a person was born (eg, as 50 or 01) and the current year (eg 03 or 04). The program should calculate the correct age of the person whether they were born in 19-- or 20-- (you can ignore those born in 18-- for the purpose of this exercise!)

Crisps
Crisp prices are notoriously difficult to compare (trust me, I've tried) because all the manufacturers seem to pack their products in packages of different weights. So if I want value for money I have to guess (or make a spreadsheet).

Create an Applet that allows the user to type in three names of crisps, three prices and three weights. By reducing all to a common price (say per 100 grams), output which of the products is the best value for money.

You will find it useful to have three sets of three text boxes ( try using panels to group the text boxes neatly - as we showed in the TestFraction example too).

Child's Play
A child is learning the alphabet. Design and write a program to accept letters input in alphabetical order until a wrong key is pressed. Present the user with a message saying how many letters they got correct as a percentage.

If you set a char identifier to a letter and then increment it, it goes to the next letter. eg:

  char letter = 'a';
   letter++;

Letter will now hold the value 'b'. Note that letter++ is the same as (letter = letter + 1) in most cases but the former (increment operator) must be used in this special case.

Resort Temperature
A program is needed to calculate the average weekly temperature at a resort given the 7 temperatures for each day of the week. Run a check to see that all boxes have been filled in.

how to

Try creating a Panel (using GridLayout as described in the how to page) that holds a Label and text field for each day of the week, something like this:

Screen shot of a Temperature Summing Applet

back to top

Related: [ Java Core | Selection Quizzes | previous TestFraction | next:AddSub]

Teaching notes

It is worth emphasizing to students that readability is much more important than conciseness when writing code.

It saves humans time.

See the note on readability below.


 
The site is partly financed by advertising revenue, partly by online teaching activities and partly by donations. If you or your organisation feel these resouces have been useful to you, please consider a donation, $9.95 is suggested. Please report any issues with the site, such as broken links, via the feedback page, thanks.

Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy.

Creative Commons License


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2009 Richard Jones, PO BOX 246, Cambridge, New Zealand;
This page was last modified: May 31, 2009