CS 1073 Introductory Programming
|
A boolean expression is one that has a value that is either true or false. Use a boolean variable to hold the value of a boolean expression.
A relational operator is one that compares two values. (In contrast, an arithmetic operator combines one or more values to produce a new arithmetic value.)
| Relational operators | ||
|
|
|
|
|
|
equal to | if ( a == 5 ) |
|
|
greater than | if ( salary > 30000 ) |
|
|
less than | if ( 0 < salary ) |
|
|
not equal to | if ( a != b ) |
|
|
greater than or equal to | if ( salary >= 10000 ) |
|
|
less than or equal to | if ( 20000 <= salary ) |
One consequent:
if (condition)
truestatement;
Two alternatives:
if (condition)
truestatement;
else
falsestatement;
Example 1: Only compute the average if there are grades. Don't divide by zero.
if ( numGrades != 0 )
average = sum/numGrades;
Example 2: Don't take the square root of a negative number.
if ( value >= 0 )
System.out.println("Square root of " + value + " = " + Math.sqrt(value));
else
System.out.println("Negative number " + value + " entered");
Question 1: What does the following do? (Trace with variables)
if ( x > y ){
temp = x;
x = y;
y = temp;
}
Ans: The values of x and y are exchanged. The
variable temp has the original value of x.
More than one statement is included in the consequent of the if in Question 1, so we use curly braces ({}) to group them.
Note the difference between test for equality(==) and the assignment operator (=).
Question 2: Assign theMin to be the smallest of x and y. Here x, y, and theMin can be either int or double Ans:
if (x <= y)
theMin = x;
else
theMin = y;
or
theMin = Math.min(x, y);
Question 3: Calculate wages as hoursWorked times hourlyRate with time and a half for overtime (hours over 40).
hoursWorked = hoursWorked*hourlyRate;
if (hoursWorked > 40)
hoursWorked += 0.5*(hoursWorked - 40)*hourlyRate; // add overtime
Question 4: Generate a random integer between 0 and 1. If the integer is 0, print out a message "You tossed heads", otherwise print out a message "You tossed tails".
Random rand = new Random();
int toss = rand.nextInt(2);
if (toss == 0)
System.out.println("You tossed heads");
else // here toss == 1
System.out.println("You tossed tails");
|
double r = Math.random();
int toss = (int)(2.0*r);
if (toss == 0)
System.out.println("You tossed heads");
else // here toss == 1
System.out.println("You tossed tails");
|
You can use as many else clauses as necessary to express multiple alteratives.
Example 3: The following code outputs a letter grade, given a grading curve.
if (score >= 90)
System.out.println("Grade is A");
else if (score >= 80)
System.out.println("Grade is B");
else if (score >= 70)
System.out.println("Grade is C");
else if(score >= 60)
System.out.println("Grade is D");
else
System.out.println("Grade is F");
System.out.println("Score is " + score);
Nested selection occurs when the either the true clause or the false clause are themselves an if statement. When the nesting occurs in the if, the code can be very confusing. You should try to avoid nested if-else statements if there are suitable alternatives. (There almost always are!)
Question 5: What happens in the following when x has value 5 and y has value 2 ?
if (x >= 0)
if (y >= x)
System.out.println(" y >= x >= 0 ");
else
System.out.println("inequality not satisfied" );
Ans: The result is probably not what you think. The Java rule for matching
else with if is that Java matches each else
with the closest preceding if that is not matched with a
closer else. (It doesn't matter how YOU indent.)
A corrected version using {} for clarity only (it behaves exactly the same as the previous one):
if (x >= 0){
if (y >= x)
System.out.println(" y >= x >= 0 ");
else
System.out.println("inequality not satisfied");
}
A better implementation eliminating the nested if-else uses the boolean operators described next:
if (y >= x && x >= 0)
System.out.println(" y >= x >= 0 ");
else
System.out.println("inequality not satisfied");
}
Question 6: Why is the following incorrect?
if (y >= x >= 0) // NOT OK, gives an ERROR
System.out.println(" y >= x >= 0 ");
Ans: The >=
can only have two operands. Evaluation occurs left to right.
The evaluation of y >= x
results in a boolean.
At this point you are
comparing a boolean
value with the int 0.
The two operands are not of compatible types, so there will be an
ERROR at this point.
Try to avoid the nesting of selection in the if clause, it
is almost always hard to figure out. Instead, reorganize your code or use
boolean operators to combine conditions.
Question 7: fill in the following table:
|
|
|
|
|
|
| false | false | |||
| false | true | |||
| true | false | |||
| true | true |
Example 4: The following outputs a message when y >= x >= 0.
if (y >= x && x >= 0)
System.out.println("y >= x >= 0");
Question 8: Rewrite the following using a single if and boolean operators. Write a sentence describing the qualifications for the offer. What kind of variable is single?
if (single)
if (gender =='M')
if( age >= 18 && age <= 26)
System.out.println("This person qualifies for our special offer");
Ans: The offer applies to single males between the ages of 18 and 26 inclusive. The
single variable is a boolean.
if (single && gender == 'M' && age >= 18 && age <= 26)
System.out.println("This person qualifies for our special offer");
Note: the comparison operators have precedence over the logical and operator,
meaning that the comparisons are done first. For this reason we can leave parentheses
out in the above code. (See the discussion of precedence below.)
The above code is equivalent to the following, which has extra parentheses for clarity:
if (single && (gender == 'M') && (age >= 18) && (age <= 26))
System.out.println("This person qualifies for our special offer");
There are often several ways of translating a statement.
Example 5: If grade is outside the interval [0, 100], indicate an error. Otherwise output the grade.
Version 1: Translate using ||:if ( choice < 0 || choice > 100 ) System.out.println("illegal choice"); else System.out.println("the grade is " + grade);Version 2: Translate using && :
if ( choice >= 0 && choice <= 100 ) System.out.println("the grade is " + grade); else System.out.println("illegal choice");
These two versions are equivalent because of De Morgan's laws, wihch state important relationships between boolean operations. These laws are particularly confusing for beginners and should be studied carefully.
!( a && b ) == ( !a ) || ( !b ) !( a || b ) == ( !a ) && ( !b )Notice above that !(choice < 0) (that is, it is NOT true that choice < 0) is the same as choice >= 0.
Strategies for simplifying expressions using De Morgan's laws:
Example 6: The following three expressions are equivalent:
The following table gives the operator precedence from highest (performed
first) to lowest (performed last)
|
|
|
|
|
|
|
|
|
|
|
logical not, unary plus, unary minus, increment, decrement |
|
|
arithmetic multiplication, division, and modulas |
|
|
arithmetic addition and subtraction |
|
|
relational inequality |
|
|
equal, not equal |
|
|
logical AND |
|
|
logical OR |
|
|
assignment operators |
Besides comparing numbers, you can compare characters and strings using the relational and equality operators. The order of character comparisons is based on the Ascii or Unicode position of each character.
|
|
|
| 'a' < 'b' | true |
| 'X' <= 'A' | false |
| '3' > '4' | false |
| '3' <= '4' | true |
| 'a' > 'A' | true |
| ('A' <= ch) && (ch <= 'Z') | true if ch contains an uppercase letter; otherwise false |
Short-circuit evaluation means that in a multiple clause boolean expression, evaluation stops as soon as the answer is determined. For example, true || X is always true no matter what X is, so there is no point finding X. Similarly, false && Y is always false regardless of Y's value. Short-circuit evaluation greatly simplifies logic in many cases.
Question 9: How would you use short-circuit evaluation to simplify the following?
if ( numscores > 0 )
if ( scoretotal/numscores > 90.0 )
System.out.println("excellent! Very good work "); >
Ans: Apply short-circuit evaluation using &&:
if ( numscores > 0 && scoretotal/numscores > 90.0 )
System.out.println("excellent! Very good work ");
The division only occurs if numscores is greater than 0.
Boolean expressions can be used in assignment statements
Example 7: boolean same;
boolean inRange;
boolean isLetter;
same = true; // same is true
same = (x==y); // same is true if x equals y otherwise false
// inRange is true if -10 < n < 10 otherwise false
inRange = (n > -10 && n < 10); // inRange is true if -10 < n < 10 otherwise false
// isLetter is true if ch is an upper or lower case letter
isLetter = ('A' <= ch && ch <='Z') || ('a' <= ch && ch <='z');
The switch statement can be used instead of multiple if's in situations where the possibilities can be enumerated.
Question 10: Convert the following if to a switch.
if ( momOrDad == 'M' || momOrDat == 'm')
System.out.println("Happy Mother's Day");
else if ( momOrDad == 'D' || momOrDat == 'd')
System.out.println("Happy Father's Day");
Ans:
switch (momOrDad) {
case 'M':
case 'm': System.out.println("Happy Mother's Day");
break;
case 'D':
case 'd': System.out.println("Happy Father's Day");
break;
}
The break must be put at the end of the clause or it continues
through the clauses. For example, if the first break is omitted in the code of Question 10,
an 'M' will cause both prints to be executed.
Example 8: The following sets the price based on watts
switch(watts) {
case 40: price = 0.50;
break;
case 60: price = 0.69;
break;
case 75: price = 0.85;
break;
case 100:
case 150: price = 1;
break;
default: price = 0;
System.out.println("No bulb in stock.");
}
The only values that you may test when using a switch statement are ordinal values:
Example 9: You may use a return instead of a break if appropriate.
switch(watts) {
case 40: return 0.50;
case 60: return 0.69;
case 75: return 0.85;
case 100:
case 150: return 1;
default: return 0;
}