Post on 21-Dec-2015
05 Simple selection 118 Apr 2023
05 Simple selection
CE00858-1: Fundamental Programming Techniques
05 Simple selection 218 Apr 2023
Objectives
In this session, we will:• introduce selection statements • use relational and logical operators in conditions• see the Java syntax for If statements• implement one-way and two-way selections• look at common mistakes in selection statements• use string comparison methods
05 Simple selection 318 Apr 2023
Control structures
• any program only uses:• sequence• selection • repetition
• so far only written programs using simple sequences• each statement performed in order
05 Simple selection 418 Apr 2023
Selection
• take different actions depending on certain conditions• condition checks current circumstances • actions are performed under those circumstances
• decide whether all situations are dealt with in the same way
• any actions done to all items are kept outside of the selection statement
if the petrol gauge in the car is on red, then stop at the next service station and buy more petrol
condition
action
Analysis of selection
• when faced with a new specification we need to decide whether all data is dealt with in the same way• if it is not, there will normally be a selection in the
program
• if a program has a selection in it, need to consider:• what data is used?• what operations are done before the selection?• what operations are done for each possibility?• what operations are done after the selection?
• to decide on the possibilities we need to split the data into groups that are processed identically
05 Simple selection 518 Apr 2023
05 Simple selection 618 Apr 2023
Conditions
• compare at least one value against another• use relational operators• may combine results of several comparisons
using logical operators
05 Simple selection 718 Apr 2023
Relational operators
• checking one thing against another• == equal to• != not equal to• > greater than• < less than• >= greater than or equal to• <= less than or equal to
• used for integers, floating points and char • avoid checking equality on floating point due
to rounding errors
05 Simple selection 818 Apr 2023
If statements in Java
if (condition)
{
statement;
}
else
{
statement;
}
condition must be enclosed by round brackets
if condition is true the next single statement is executed
braces are needed to block more than one statement
else is optional
indentation is used to show program structure
05 Simple selection 918 Apr 2023
One-way selection example – Discount
• performs actions when a condition is true
• problem:• process order discounts:
• prompt user for number of items to order and calculate cost of order at 50p per item
• if order more than 100 apply 10% discount• output amount to be paid
05 Simple selection 1018 Apr 2023
Discount analysis
• what data is used?• quantity: positive integer input by user• cost: double calculated by program
• need selection as quantity over 100 has discount• what operations are done before the selection?
• create Scanner • prompt user for quantity• input quantity• calculate cost: quantity * 0.5 (double)
• what operations are done if quantity over 100?• apply 10% discount
• what operations are done if quantity 100 or less?• none
• what operations are done after the selection?• output cost
05 Simple selection 1118 Apr 2023
Discount code
//process order discountsScanner myKeyboard = new Scanner(System.in);System.out.print("Enter quantity: ");int quantity = myKeyboard.nextInt();double cost = quantity * 0.5;
//apply 10% discount if more than 100 items orderedif ( quantity > 100 ){
cost = cost * 0.9;}System.out.println("Cost of order: " + cost);
only executed if condition true
Discount.java
05 Simple selection 1218 Apr 2023
Two-way selection example – BankBalance
• performs one set of actions if condition is true and another if false
• problem:• check user’s bank balance:
• if overdrawn output "overdrawn", otherwise output "in credit"
05 Simple selection 1318 Apr 2023
BankBalance analysis
• what data is used?• balance: double input by user
• need selection as different messages output based on balance
• what operations are done before the selection?• create Scanner• prompt user for balance• input balance
• what operations done if balance less than 0?• output "overdrawn"
• what operations done if balance 0 or over?• output "in credit"
• what operations are done after the selection?• none
05 Simple selection 1418 Apr 2023
BankBalance code
//check user’s bank balanceScanner myKeyboard = new Scanner(System.in);System.out.print("Enter balance: ");double balance = myKeyboard.nextDouble();
//output message giving status of accountif ( balance < 0.0 ){
System.out.println("Overdrawn");}else{
System.out.println("In credit");}
executed if condition true
executed if condition false
BankBalance.java
05 Simple selection 1518 Apr 2023
Common mistake 1
• problem...
int num1 = 3;if ( num1 < 0 )
System.out.println("num1 is " + num1);System.out.println("num1 is negative");
05 Simple selection 1618 Apr 2023
Common mistake 2
• problem...
int num1 = 3;if ( num1 < 0 ) ;{
System.out.println("num1 is " + num1);System.out.println("num1 is negative");
}
05 Simple selection 1718 Apr 2023
Common mistake 3
• problem...
int num1 = 3;if ( num1 = 0 ) {
System.out.println("num1 is " + num1);System.out.println("num1 is negative");
}
05 Simple selection 1818 Apr 2023
Logical operators
• used to combine results of different tests• brackets can be used to clarify meaning
• ! NOT - opposite of original expression
• && AND - true if both expressions true• || OR - true if either expression true
• each condition part must be correctly formed
05 Simple selection 1918 Apr 2023
Logical operators example – Divisible
• problem:• output if number is divisible by 3 and 5
• analysis:• what data is used?
• number: integer input by user
• selection needed as message only output for numbers divisible by 3 and 5
• what operations are done before the selection?• create Scanner• prompt user for number• input number
• what operations are done if the number is divisible by 3 and 5?• output "divisible by 3 and 5"
• what operations are done if the number is not divisible by 3 and 5?
• none
• what operations are done after the selection?• none
05 Simple selection 2018 Apr 2023
Divisible code
//check divisible by 3 and 5Scanner myKeyboard = new Scanner(System.in);System.out.print("Enter number: ");int number = myKeyboard.nextInt();
//check whether number is divisible by 3 and by 5if (( number % 3 == 0 ) && (number % 5 == 0)){
System.out.println("Divisible by 3 and 5");}
Divisible.java
05 Simple selection 2118 Apr 2023
Checking for ranges
• && and || can be used to check if a value is in range:
//check whether person can not go on 18 – 35 holidayif (( age < 18 ) || (age > 35)){
System.out.println("You've missed out!");}
//check whether person can go on 18 – 35 holidayif (( age >= 18 ) && (age <= 35)){
System.out.println("Have a great holiday!");}
check for value in range
check for value out of range
05 Simple selection 2218 Apr 2023
Comparing strings
• capital letters precede lower case• cannot use relational operators on Strings• need to use methods in String class• to check if strings are equal:
• to check if strings are equal, regardless of case:
• to check if a string ends with another string:
if (greeting.equals("Hello")) ...
if (greeting.equalsIgnoreCase("HeLLo")) ...
if (greeting.endsWith("lo")) ...
05 Simple selection 2318 Apr 2023
Comparing strings example – Access
• problem:• output message granting access based on user type• user is either staff or student
• analysis:• what data is used?
• userType: string input by user, either "staff" or "student"• selection needed as staff and students access different facilities• what operations are done before the selection?
• create Scanner• prompt user for userType• input userType
• what operations are done if userType is "staff"• output "Access to staff facilities"
• what operations are done if userType is not "staff"• output "Access to student facilities"
• what operations are done after the selection?• none
05 Simple selection 2418 Apr 2023
Access code
//output message granting access dependent on user typeScanner myKeyboard = new Scanner(System.in);System.out.print("Enter user type: ");String userType = myKeyboard.nextLine();
//check user typeif (userType.equalsIgnoreCase("staff")){
System.out.println("Access to staff facilities");}else{
System.out.println("Access to student facilities");}
Access.java
05 Simple selection 2518 Apr 2023
Summary
In this session we have:• implemented simple selection statements • used relational and logical operators• implemented string comparison using methods
In the next session we will:• look at testing selection statements