This lab discusses selections and provides examples of if statement, nested if, and switch. It also covers logical operators and relational operators. It gives many examples to help the student develop logical think and structure computer logic.
2. Introduction
This lab discusses selections and provides examples of if statement, nested if, and
switch. It also covers logical operators and relational operators. It gives many
examples to help the student develop logical think and structure computer logic.
Skill-set
By completing this lab, the students will develop the following skills:
• Build accurate, simple and nested if statement
• Use appropriate logical and relational operators to solve
programming problems that require the use of selection
• Develop a user menu using a combination of a switch and
while loop
How to use this lab?
Follow the lab instruction in step by step and complete all exercises. Watch
the associated videos.
Modify the examples to and exercises to experiment with different scenarios
to solve a similar problem.
Click the QR code to access the videos and PowerPoint icon to access the
associated PowerPoints.
3. 3
Why selection is needed?
In our life, we are required to make decision-based on certain conditions. For
example, if you are on the road and find the intersection, you decide to go right,
left or straight based on your destination and the fast or less traffic road.
In programming, there are situations when you need to apply a specific process
when a condition is true and another process when it is false.
The Java Language uses two essential commands to allow us to select what
process should be executed in case of one or more conditions are met. These
two commands are: if ... else and switch.
A simple if statement structure
Here is a simple structure of an if statement|:
If
(condition)
Process1
Process2
The rest of the
code
true
false
In the above structure, when the condition is met (true), the first process is
executed. When the condition is false, process 2 is executed. A process can be
one or more lines of call. You may also call another function/method as part of
your process or perform some calculations.
4. 4
Building conditions
The condition involved comparing values. Here is a simple example:
Line 3 declares and initiates x as 100.
In line 4 we have the condition x>5, which can be read as
Is x more than 50?.
The answer in this case is true. X is 100, which is more than 50. Therefor the
program will go to line 5 and display
Change line 3 to be int x = 45; What output will you get in this case? Explain briefly
what has happened?
Exercise
5. 5
Use of brackets if statement
• The condition should be included between two brackets of this type ( )
• An opened and closed braces { } should follow the condition. The process
that must be executed in case the condition is true should be included
between these two braces. See line 4 to line 6. When there is only one
line needed for the process, these two braces become optional.
• The same applies to the else block.
Indentation
Using consistent and appropriate indentation will improve the readability of
your code.
• In the above example, please note that line 4 is pushed to the right to
show that it is part of the process that will be executed when the condition
is met. The same for line 8.
• Also, lines from 3 to 9 are pushed/indented to right to show they are all
part of the main function.
Indentation is optional for Java Language. However, it is must for some other
languages including Python.
Here is another example:
6. 6
The Relational Operators
When comparing two variables, you need to use a rational operator. All
programming languages use complete relationship operators. The table below
summarizes the relational operators available in the Java Language.
• It is important to note that to compare if two values are equal,
then you use == and not only =.
• A single = is used only to assign a value to the variable, == is used
to compare or check the value of a variable.
Also, note >= is correct by => is incorrect.
7. 7
Exercise
What will be the result of this code and why?
Change x value in line 3 to 20. What will be the result and why?
If you need to check if y is true, then you need an if statement. See line 5 of
this code.
Line 5 is using the condition in line 4 to check the value of y. When y is true,
the message “Y is equal to 50.” is displayed, else “Y is NOT equal to 50.” is
displayed.
8. 8
Logical Operators
When you have more than one condition, then you need to link them using
logical operators. We will use only 3 logical operators that are AND, OR,
and NOT.
Assume we have two conditions.
• If both conditions must be met, then we use and. The symbol for and is
&&
• If we need at least one of the two conditions to be met, then we use or.
The symbol for or ||
• If we want to reverse the logic, then we use logical not, The symbol is !
The operator (! logical not) has a limited use cases. Therefore, we will focus
on && and ||.
In the following table, assume boolean variables A holds true and variable
B holds false
9. 9
An Example
Assume there is an insurance company that provides a rate of 3.5% for cars
with price value more than or equal 10,000 and model of 2015 or above.
Other cars have to pay 4.5% rate to be insured by this company.
Here is the code to solve this problem.
• Please focus on line 13. You will notice that we have used && to ensure
that both conditions are met to provide a 3.5% rate.
• If the answer is true, then line 14 is executed. For any car that does not
meet this condition, line 18 is executed.
• Line 20 is outside the if statement and executed after the calculation of
insurance value.
• You are expected to be familiar with the rest of the code.
10. 10
Exercise
What is the output of this code and why?
Change line 4 to int y = 20; What is the output in this case any why?
11. 11
Exercise
What is the output of this code and why?
Change line 4 to int y = 50; What is the output in this case any why?
12. 12
Examine this code carefully. How many conditions do we have?
Line 7 requires that x to be more than 70 and either x<5 or y<40. If x is not
more than 10, the rest of the conditions are ignored.
What is the result of this code?
What will happen if you change x value in line 3 to 11?
13. 13
Nested if statement
Condition
1
Condition
2Process 1
The rest of code
Process 2 Process 3
true
true
false
false
When you have an if statement inside another if statement, this is referred to as
nested if. Nested if is a very common in programming to deal with more complex
conditions. However, they are logical, easy to follow and implement. Here is an
example of nested if structure.
• Process 1 is executed when the result of condition1 is true. In this case,
condition2 is ignored.
• However, if the result of condition1 is false, condition2 is checked. If
condition 2 is true, process 2 is executed.
• If both condition1 and condition2 are false, then process 3 is executed.
14. 14
An example - nested if statement
Examine this code. What do you think the result in this case?
• Given that x = 5 and y=30, the result of line 8 is false. Simply the
condition y<30 is not met as y=30 and not less than 30. In this case, the
execution is moved to line 11.
• The result of line 11 is also false, because y is not less than 5 or more
than or equal 35. Basically 3 is not less than 5 and 30 is not more than
or equal 35. None of these conditions is met
• The last option is line 16. The result is 3 * 5 = 150.
15. 15
An exercise - nested if statement
Examine this code. What do you think the result in this case?
16. 16
switch in Java
If you need to select between discrete values for example 1, 2, 3, 4, etc. Or “A”, “B”, “C”,
etc., then switch is a good option.
Here is an example that allow the user to enter a number and check:
• If the entered number is 1, then the message “You have entered 1” will be
displayed.
• If the number is 2 the message “You have enter 2” is displayed
• However, if user enters a different number apart of 1 and 2, the messaged “You
entered an invalid number” will be displayed.
The switch structure has 5 main components that are:
1. The switch command (line 8),
2. The switch parameter (in this example the variable option),
3. A case for every option (lines 9 and 12)
4. A default which is executed if the entered value is not one the option
(line 15).
5. It is important to have the keyword break at the end of each case
including the default option.
One of the common use cases of switch is creating user-menu.
17. 17
switch and while
To create a user menu, you need include the switch inside a while loop as in
this example.
The while command in line 8 repeats all lines from 9 to 29 while the user did
not enter 3. As soon as the user enter 3 the program stops and the message
“This is the end.” is displayed.
18. 18
1. Develop a Java program that reads an integer number and determines if the number entered is
'positive', 'negative', or 'zero' and outputs the result on the screen.
2. Develop a Java program that reads an integer number, determines if the number is odd or even
and outputs a message on the screen indicating the number is odd or even.
3. Develop a Java program that will accept marks in the range of 0 to 100 and will determine the
grade according to data given in the table below:
00 – 59 F
60 – 64 D
65 – 74 C
75 – 89 B
90 – 100 A
Your program should output an error message if the user enters a mark that is outside the range 0 –
100.
4. Write a Java program that will receive two integer numbers and display their sum, difference,
product, and quotient. The quotient (first integer divided by second integer) is only to be
performed if the second integer does not equal zero
5. A program is required to read a customer’s name, a purchase amount and a discount code. The
discount code will be one of the following:
A no discount (0%)
B small discount (3%)
C medium discount (12%)
D big discount (20%)
The program must then compute the discount amount and the sales total and then print the
customer’s name, purchase amount, discount amount and the total due.
6. Develop a program that asks the user about his grade and displays a message based on the grade
entered. The program should display “Excellent” for an A, “Very Good” for a B, “Good” for a C,
“Acceptable” for a D, and “Failed you have to repeat the course” for a F. The case of grade entered
should not matter. For example capital “A” or small “a” are similar.
7. UAE post office charges parcels per kilogram. If the parcel is 5 kilos or less it charges AED 10 per
kilogram. If the parcel is 10 kilos or less but greater than 5 kilos it charges AED 8 per kilogram. If the
parcel is more than 10 kilos it charges AED 5 per kilogram. Develop a program that asks the user to
enter the weight and displays the weight and charge on the screen.
Exercises