View
222
Download
2
Category
Preview:
Citation preview
Chapter 5– Making DecisionsChapter 5– Making Decisions
Dr. Jim BurnsDr. Jim Burns
In Java, the simplest statement..In Java, the simplest statement..
Is the if(..) statementIs the if(..) statement
if(someVariable==10) if(someVariable==10) System.out.println(“The value of System.out.println(“The value of someVariable is 10”);someVariable is 10”);
if(someVariable==10)…if(someVariable==10)…
The if(…) statement evaluates to The if(…) statement evaluates to truetrue when the value of someVariable is 10 and when the value of someVariable is 10 and to to falsefalse when the value of someVariable is when the value of someVariable is not 10not 10
The System.out.println(..) only executes The System.out.println(..) only executes when the if(..) evaluates to truewhen the if(..) evaluates to true
In if(..) statements the Boolean expression In if(..) statements the Boolean expression must appear within parenthesesmust appear within parentheses
The statement ends after the action to be The statement ends after the action to be taken if the Boolean expression is true is taken if the Boolean expression is true is declareddeclared
Then the semicolon appearsThen the semicolon appears
Irregardless of whether the Boolean Irregardless of whether the Boolean expression is true or false, execution will expression is true or false, execution will continue with the next statementcontinue with the next statement
The System.out.println() statement The System.out.println() statement executes only if the statement is executes only if the statement is truetrue
The Result of every if(…)The Result of every if(…)
Every if(..) produced a Boolean result…Every if(..) produced a Boolean result…either either truetrue or or falsefalse
Single-alternative if(..)Single-alternative if(..)
if(someVariable==10) if(someVariable==10) System.out.println(“The value of System.out.println(“The value of someVariable is 10”);someVariable is 10”);
Only one action is performed based on the Only one action is performed based on the result of the Boolean expressionresult of the Boolean expression
Dual-alternative if(..)Dual-alternative if(..)
Requires the use of the Requires the use of the else else keywordkeyword
if(someVariable==10) if(someVariable==10) System.out.println(“The value of System.out.println(“The value of someVariable is 10”);someVariable is 10”);
elseelse System.out.println(“No, it’s not”);System.out.println(“No, it’s not”);
Nested IF’sNested IF’s
If(itemsSold > 3)If(itemsSold > 3)
if(totalValue > 1000)if(totalValue > 1000)
bonus = 50;bonus = 50;
elseelse
bonus = 25;bonus = 25;
elseelse
bonus = 10;bonus = 10;
Using Multiple statements in an Using Multiple statements in an if or if…else structureif or if…else structure
Must use braces to designate blocksMust use braces to designate blocks
If(hoursWorked > 40)If(hoursWorked > 40)
{{
regularPay = 40 * rate;regularPay = 40 * rate;
overtimePay = (hoursWorked – 40) * 1.5 overtimePay = (hoursWorked – 40) * 1.5 * rate* rate
System.out.println(“Regular pay is “ + System.out.println(“Regular pay is “ + regularPay);regularPay);
System.out.println(“Overtime pay is “ + System.out.println(“Overtime pay is “ + overtimePay);overtimePay);
}}
import javax.swing.JOptionPane;import javax.swing.JOptionPane;public class Payrollpublic class Payroll{{ public static void main(String[] args)public static void main(String[] args) {{ String hoursString;String hoursString; double rate = 20.00;double rate = 20.00; double hoursWorked;double hoursWorked; double regularPay;double regularPay; double overtimePay;double overtimePay; hoursString = JOptionPane.showInputDialog(null,hoursString = JOptionPane.showInputDialog(null, "How many hours did you work this week?");"How many hours did you work this week?"); hoursWorked = Double.parseDouble(hoursString);hoursWorked = Double.parseDouble(hoursString); if(hoursWorked > 40)if(hoursWorked > 40) {{ regularPay = 40 * rate;regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate;overtimePay = (hoursWorked - 40) * 1.5 * rate; }} elseelse {{ regularPay = hoursWorked * rate;regularPay = hoursWorked * rate; overtimePay = 0.0;overtimePay = 0.0; }} JOptionPane.showMessageDialog(null, "Regular pay is " +JOptionPane.showMessageDialog(null, "Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay);regularPay + "\nOvertime pay is " + overtimePay); System.exit(0);System.exit(0); }}
}}
if(hoursWorked > 40)if(hoursWorked > 40) {{ regularPay = 40 * rate;regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 overtimePay = (hoursWorked - 40) * 1.5
* rate;* rate; }} elseelse {{ regularPay = hoursWorked * rate;regularPay = hoursWorked * rate; overtimePay = 0.0;overtimePay = 0.0; }}
if(…) cannot ask ..if(…) cannot ask ..
““What number did the user enter?”What number did the user enter?”
INSTEAD…INSTEAD…
““Did the user enter a 1?”Did the user enter a 1?”
““Did the user enter a 2?”Did the user enter a 2?”
““Did the user enter a 3?”Did the user enter a 3?”
Observe the use of Observe the use of elseelse
If(itemsSold > 3)If(itemsSold > 3)
if(totalValue > 1000)if(totalValue > 1000)
bonus = 50;bonus = 50;
elseelse
bonus = 25;bonus = 25;
elseelse
bonus = 10;bonus = 10;
Using logical AND and OR Using logical AND and OR statementsstatements
Rather than nested if’s, can AND two or Rather than nested if’s, can AND two or more Boolean expressions togethermore Boolean expressions together– The result is The result is truetrue only if all Boolean only if all Boolean
expressions are expressions are truetrue
Bonus = 0;Bonus = 0;
If(itemsSold > 3 && totalValue > 1000) If(itemsSold > 3 && totalValue > 1000) bonus = 50;bonus = 50;
The code above works like…
Bonus = 0;
If(itemsSold > 3)
if(totalValue > 1000)
bonus = 50;
So why use the && operator??
It makes your code more concise, less error-prone, and easier to understand
Note that when you use the && operator, you must include a complete Boolean expression on each side of the &&
bonus = 0;
If(itemsSold > 100) bonus = 200;
else if(totalValue > 3000) bonus = 200;
Accomplishes the same as…..
bonus = 0;
If(itemsSold > 100 || totalValue > 3000) bonus = 200;
Avoiding Common errors when Avoiding Common errors when making decisionsmaking decisions
Using the assignment operator instead of Using the assignment operator instead of the comparison operator when testing for the comparison operator when testing for equalityequality
Inserting a semicolon after the Boolean Inserting a semicolon after the Boolean expression in an if statement expression in an if statement
Failing to block a set of statements with Failing to block a set of statements with curly braces when several statements curly braces when several statements depend on the depend on the ifif or the or the elseelse statement statement
Still more common errors…
Failing to include a complete Boolean expression on each side of an && or || operator in an if statement
Performing a range check incorrectly or inefficiently
Using the wrong operator with AND and OR
Performing accurate and Performing accurate and efficient range checksefficient range checks
A range check is a series of A range check is a series of ifif statements statements that determine whether a value falls within that determine whether a value falls within a specified rangea specified range
Incorrect range check code
If(saleAmount >= 1000) commissionRate = .08;
If(saleAmount >= 500) commissionRate = .06;
If(saleAmount <= 499) commissionRate = .05;
Correct range check code…but inefficient
If(saleAmount >= 1000) commissionRate = .08;
else if(saleAmount >= 500) commissionRate = .06;
else if(saleAmount <= 499) commissionRate = 0.05;
.
.
else commissionRate = 0.05;
Using AND and OR Using AND and OR appropriatelyappropriately
The boss might say “Print an error The boss might say “Print an error message when an employee’s hourly rate message when an employee’s hourly rate is under $5.65 and when an employee’s is under $5.65 and when an employee’s hourly pay rate is over $60”hourly pay rate is over $60”
If(payRate < 5.65 && payRate > 60) If(payRate < 5.65 && payRate > 60) System.out.println(“Error in pay rate”);System.out.println(“Error in pay rate”);
What is wrong with this and how do you fix What is wrong with this and how do you fix the problem?the problem?
ANDing two Boolean expressions together
Boolean Expression 1
Boolean
Expression 2
Result of AND ing them
true true true
true false false
false true false
false false false
Both of the Boolean expressions have to be true in order for the result of ANDing them to return a value of true
ORing two Boolean expressions together
Boolean Expression 1
Boolean
Expression 2
Result of OR ing them
true true true
true false true
false true true
false false false
When ORing, if either Boolean expression is true, the result of ORing is true.
It’s only when both of the Boolean expressions are false that the result of ORing is false
Using the switch statementUsing the switch statement
if(year == 1) System.out.println(“Freshman”);if(year == 1) System.out.println(“Freshman”);
else if(year == 2) else if(year == 2) System.out.println(“Sophmore”);System.out.println(“Sophmore”);
else if(year == 3) System.out.println(“Junior”);else if(year == 3) System.out.println(“Junior”);
else if(year == 4) System.out.println(“Senior”);else if(year == 4) System.out.println(“Senior”);
else System.out.println(“Invalid year”);else System.out.println(“Invalid year”);
Instead use the switch statement..Instead use the switch statement..
Int year;//get year value from user input or databaseSwitch(year){
case 1:System.out.println(“Freshman”);break;
case 2:System.out.println(“Sophomore”);break;
case 3:System.out.println(“Junior”);break;
case 4:System.out.println(“Senior”);break;
default:System.out.println(“Invalid year”);
}
Int year;//get year value from user input or databaseSwitch(year){
case 1:System.out.println(“Freshman”);
case 2:System.out.println(“Sophomore”);
case 3:System.out.println(“Junior”);
case 4:System.out.println(“Senior”);
default:System.out.println(“Invalid year”);
}
Int year;//get year value from user input or databaseSwitch(year){
case 1:System.out.println(“Freshman”); Break;
case 2:System.out.println(“Sophomore”); Break;
case 3:System.out.println(“Junior”); Break;
case 4:System.out.println(“Senior”); Break;
default:System.out.println(“Invalid year”);
In the code above….
The switch structure begins by evaluating the year variable in the switch statement
If year is equal to the first case value, which is one, “Freshman” is printed
The break statements bypass the rest of the switch structure and execution continues with the statement following the closing curly brace of the switch structure
switch()
What is the data type of the argument of a switch() statement?
Int, char, short and byte
Does a semicolon follow a switch statement?
What delimiter follows each case statement?
Are the break statements necessary for the code to work right?
int department;int department;
String supervisor;String supervisor;
// Statement to get department value// Statement to get department value
Switch (department)Switch (department)
{{
case 1:case 1:
case 2:case 2:
case 3:case 3:
supervisor = “Jones”;supervisor = “Jones”;
Break;Break;
case 4:case 4:
supervisor = “Staples”;supervisor = “Staples”;
break;break;
case 5;case 5;
supervisor = “Tejano”;supervisor = “Tejano”;
break;break;
default:default:
System.out.println(“Invalid System.out.println(“Invalid department code”);department code”);
}}
Using the conditional AND NOT Using the conditional AND NOT OperatorsOperators
Consider the following code…Consider the following code…
If(a < b) smallerNum = a;If(a < b) smallerNum = a;
else smallerNum = b;else smallerNum = b;
smallerNum = (a < b) ? A : b;smallerNum = (a < b) ? A : b;
The conditional operator uses the ? and the : to The conditional operator uses the ? and the : to separate three expressions; the first expression separate three expressions; the first expression must be a Boolean expressionmust be a Boolean expression
Using the NOT OperatorUsing the NOT Operator
You use the NOT operator which is written You use the NOT operator which is written as the exclamation point (!), to negate the as the exclamation point (!), to negate the result of any Boolean expressionresult of any Boolean expression
If (age <= 25) premium = 200;If (age <= 25) premium = 200;
else premium = 125;else premium = 125;
If(!(age <= 25)) premium = 125;If(!(age <= 25)) premium = 125;
else premium = 200;else premium = 200;
Understanding precedenceUnderstanding precedencePrecedence Operator(s) Symbols
Highest Logical NOT !
Intermediate Multiplication, division, modulus
* / %
Addition, subtraction + -
Relational > < >= <=
Equality == !=
Logical AND &&
Logical OR ||
Conditional ? :
lowest Assignment =
PrecedencePrecedence
Order of precedence agrees with common Order of precedence agrees with common algebraic practicealgebraic practice
Notice that the and && operator is always Notice that the and && operator is always evaluated before the or || operatorevaluated before the or || operator
ExampleExampleConsider an auto insurance sys that determines Consider an auto insurance sys that determines the amount of premium to chargethe amount of premium to charge
Additional premium is charged to a driver who Additional premium is charged to a driver who meets both of the following criteria:meets both of the following criteria:– Has more than two traffic tickets or is under 25 years Has more than two traffic tickets or is under 25 years
oldold– Is maleIs male
Consider a 30 year old female driver with three Consider a 30 year old female driver with three traffic ticketstraffic tickets
Code implementations
// assigns extra premiums incorrectly
if(trafficTickets > 2 || age < 25 && gender == ‘M’) extraPremium = 200;
// assigns extra premiums correctly
If((trafficTickets > 2 || age < 25) && gender == ‘M’) extraPremium = 200;
Remember, do what is inside () first
import javax.swing.JOptionPane;public class Payroll{ public static void main(String[] args) { String hoursString; double rate = 20.00; double hoursWorked; double regularPay; double overtimePay; hoursString = JOptionPane.showInputDialog(null, "How many hours did you work this week?"); hoursWorked =
Double.parseDouble(hoursString); if(hoursWorked > 40) { regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; } JOptionPane.showMessageDialog(null, "Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay); System.exit(0); }}
Recommended