|
|
||
| You are here: | ||
|
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 ] 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 ) 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) 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) The most frequently used arithmetic conditions are:
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') This example also shows how to put a quote inside a String literal (use the escape character \). The conditions can be combined with logical and (&&) and or (||) symbols, for example: if ( (ch == 'y') || (ch == 'Y') ) 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) ) The condition is true if both conditions are true, otherwise false. The and (&&) condition is done before the or (||) if brackets are not used: 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")) 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) Remember that you may see if statements without braces in other people's code: int x = 9; What's the value of answer? flip, flop or fly? Turn to the quiz page to find out if you are right! back to topThe 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); Some programmers like the switch, some don't. The main differences between switch and an if else chain are:
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. Before attempting the exercises you might like to look at an example Applet using selection - the AddSub Applet . In addition to those mentioned in the text :-) CD Store
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? Crisps 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 If you set a char identifier to a letter and then increment it, it goes to the next letter. eg: char letter = 'a'; 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
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. |
|
|
|||
|
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. 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 |