CPPROG2 - Lesson 5 Making Decisions
CPPROG2 - Lesson 5 Making Decisions
Reference Materials:
The programming you’re doing now is sequential programming, meaning the code is executed
from top to bottom. It’s very linear, in that each and every line of code will be read, starting with
the first line of code you write and ending at the last line.
But you don’t always want your programs to work like that. Often, you want code to be executed
only if certain conditions are met. For example, you might want one message to display if a user
is below the age of 18 and a different message if he or she is 18 or older. You want to control the
flow of the program for yourself. You can do this with conditional logic.
Conditional logic is mainly about the IF word: IF user is less than 18 then display this message; IF
user is 18 or older then display that message. Fortunately, it’s very easy to use conditional logic
in Java. Let’s start with IF Statements.
IF STATEMENTS
Executing code when one thing happens rather than something else is so common in
programming that that the IF Statement has been developed. The structure of the IF Statement
in Java is this:
if ( Statement ) {
You start with the word IF (in lowercase) and a pair of round brackets. You then use a pair of
curly brackets to section off a chunk of code. This chunk of code is code that you only want to
execute IF your condition is met. The condition itself goes between round brackets:
if ( user < 18 ) {
This condition says “IF user is less than 18”. But instead of saying “is less than” we use the
shorthand notation of the left-pointing angle bracket ( < ). IF the user is less than 18 then we
want something to happen, to display a message, for example:
if ( user < 18 ) {
OBJECT-ORIENTED PROGRAMMING JAVA Programming
// DISPLAY MESSAGE
}
If the user is not less than 18 then the code between the curly brackets will be skipped, and the
program continues on its way, downwards towards the last line of code. Whatever you type
between the curly brackets will only be executed IF the condition is met, and this condition goes
between the round brackets.
Before we try this out, another shorthand notation is this symbol >. The right pointing angle
bracket means “greater than”. Our IF Statement above can be amended slightly to check for
users who are greater than 18:
if ( user > 18 ) {
// DISPLAY MESSAGE
}
The only thing new in this code is the > symbol. The condition now checks for users who are
greater than 18.
But the condition doesn’t check for people who are exactly 18, just those greater than 18. If you
want to check for those who are 18 or over, you can say “greater than or equal to”. The symbols
for this are the greater than sign ( > ) followed by an equals sign ( = ):
if ( user >= 18 ) {
// DISPLAY MESSAGE
}
You can also check for “less than or equal to” in a similar way:
if ( user <= 18 ) {
// DISPLAY MESSAGE
}
The above code contains a less than symbol ( < ) followed by the equals sign.
We’ve set up an integer variable, and assigned a value of 17 to it. The IF statement checks for
“less than 18”. So the message between the curly brackets should be printed out.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
Now change the value for the user variable from 17 to 18. Run your program again. You should
see this:
Figure 6-3
So the program runs OK, with no error messages. It’s just that nothing gets printed out. The
reason is that the message code is between the curly brackets of the IF Statement. And the IF
Statement is checking for values less than 18. IF the condition is not met, Java ignores the curly
brackets altogether and moves on
IF … ELSE
Instead of using IF Statement, you can use an IF … ELSE Statement instead. Here’s the structure
of an IF … ELSE statement:
if ( condition_to_test ) {
} else {
The first line starts with if, followed by the condition you want to test for. This goes between
two round brackets. Again, curly brackets are used to section off the different choices. The
second choice goes after the word else and between its own curly brackets. Here’s our code
again that checks a user’s age:
So there are only two choices here: either the user is 18 or younger, or the user is older than
that. Adapt your code to match that in the image above and try it out. You should find that the
first message prints out. Now change the value of the user variable to 20 and run the code again.
The message between the ELSE curly brackets should display in the Output window.
IF … ELSE IF
You can test for more than two choices. For example, what if we wanted to test for more age
ranges, say 19 to 39, and 40 and over? For more than two choices, the IF … ELSE IF statement
can be used. The structure of an IF … ELSE IF is this:
if ( condition_one) {
} else if ( condition_two ) {
} else {
else if ( condition_two ) {
So the first IF tests for condition number one (18 or under, for example). Next comes else if,
followed by a pair of round brackets. The second condition goes between these new round
brackets. Anything not caught by the first two conditions will be caught be the final else. Again,
code is sectioned off using curly brackets, with each if, else if, or else having its own pair of curly
brackets. Miss one out and you’ll get error messages.
Before trying out some new code, you’ll need to learn some more conditional operators:
OPERATOR DEFINITION
> Greater Than
< Less Than
>= Greater Than or Equal To
<= Less Than or Equal To
&& AND
|| OR
== HAS A VALUE OF
! NOT
Table 5-1 Conditional Operators
The two ampersand symbols is used to test for more than one condition at the same time. We
can use it to test for two age ranges:
Here, we want to check if the user is older than 18 but younger than 40. Remember, we’re trying
to check what is inside of the user variable. The first condition is “Greater than 18” ( user > 18 ).
The second condition is “Less than 40” ( user < 40). In between the two we have our AND
operator ( && ). So the whole line says “else if user is greater than 18 AND user is less than 40.”
We’ll get to the other three conditional operators in a moment. But here’s some new code to try
out:
OBJECT-ORIENTED PROGRAMMING JAVA Programming
Run your program and test it out. You should be able to guess what it will print out before running
it. Because we have a value of 21 for the user variable the message between the curly brackets
of else if will display in the Output window.
NESTED IF STATEMENTS
You can nest IF Statements. (This also applies to IF ... ELSE and IF ... ELSE IF statements.) Nesting
an IF Statement just means putting one IF Statement inside of another. For example, suppose
you want to find out if somebody is younger than 18, but older than 16. You want to display a
different message for the over 16s. You start with the first IF Statement:
if (user < 19 ) {
System.out.println( "18 or younger");
}
To check for over 16, you can place a second IF Statement inside of the one you already have.
The format is the same:
if (user < 19 ) {
if (user > 16 || user < 19 ) {
System.out.println( "You are 17 or 18");
}
}
So the first IF Statement catches the user variable if it's less than 19. The second IF Statement
narrows the user variable down even further, for ages over 16 and under 19. To print different
messages, you can have an IF ... ELSE statement instead of the IF Statement above:
OBJECT-ORIENTED PROGRAMMING JAVA Programming
Notice where all the curly brackets are in the code: get one wrong and your program won't run.
Nested IF Statements can be tricky, but all you're trying to do is to narrow down the choices.
BOOLEAN VALUES
A Boolean value is one with two choices: true or false, yes or no, 1 or 0. In Java, there is a variable
type for Boolean values:
So instead of typing int or double or string, you just type boolean (with a lower case “b”).
After the name of your variable, you can assign a value of either true or false. Notice that the
assignment operator is a single equals sign ( = ). If you want to check if a variable “has a value of”
something, you need two equal signs ( = =).
So the first IF Statement checks if the user variable has a value of true. The else part checks if it
is false. You don’t need to say “else if ( user == false)”. After all, if something is not true then it’s
false. So you can just use else: there’s only two choices with boolean values.
The only other conditional operator on our lists is the NOT operator. You can use this with
boolean values. Have a look at the following code:
if (!user) {
System.out.println("it's false");
} else {
System.out.println("it's true");
}
It’s almost the same as the other boolean code, except for this line:
OBJECT-ORIENTED PROGRAMMING JAVA Programming
if (!user) {
This time, we have our NOT operator before the user variable. The NOT operator is a single
exclamation mark ( ! ) and it goes before the variable you’re trying to test. It’s testing for
negation, which means that it’s testing for the opposite of what the value actually is. Because
the user variable is set to true then !user will test for false values. If user was set to false then
!user would test for true values. Think of it like this: if something is NOT true then what is it? Or
if it’s NOT false then what?
SWITCH STATEMENTS
Another way to control the flow of your programs is with something called a switch statement.
A switch statement gives you the option to test for a range of values for your variables. They can
be used instead of long, complex if … else if statements. The structure of the switch statement is
this:
switch ( variable_to_test ) {
case value:
code_here;
break;
case value:
code_here;
break;
default:
values_not_caught_above;
}
So you start with the word switch, followed by a pair of round brackets. The variable you want
to check goes between the round brackets of switch. You then have a pair of curly brackets. The
other parts of the switch statement all go between the two curly brackets. For every value that
you want to check, you need the word case. You then have the value you want to check for:
case value:
After case value comes a colon. You then put what you want to happen if the value matches. This
is your code that you want executed. The keyword break is needed to break out of each case of
the switch statement.
The default value at the end is optional. It can be included if there are other values that can be
held in your variable but that you haven’t checked for elsewhere in the switch statement.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
The first thing the code does is to set a value to test for. Again, we’ve set up an integer variable
and called it user. We’ve set the value to 18. The switch statement will check the user variable
and see what’s in it. It will then go through each of the case statements in turn. When it finds
one that matches, it will stop and execute the code for that case. It will then break out of the
switch statement.
Try the program out. Enter various values for the user variable and see what happens.
Sadly, you can’t test for a range of values after case, just the one value. So you can’t do this:
So the above line tests for a range of values, from 1 to 4. But you have to “spell out” each value.
(Notice where all the case and colons are.)