Boolean Expressions

Download Report

Transcript Boolean Expressions

Java the UML Way
http://www.tisip.no/JavaTheUmlWay/
Selection as a Control Structure
Control structures
The Calculator class with a client program
Blocks inside methods
The if statement has two forms
Curly braces and indents
Nested if and multiple choice statements
Decision tables
Boolean expressions
Comparing strings
Short-circuit evaluation
The switch statement
Comparing computed decimal numerals
version 2002-04-17
page 2
page 3-5
page 6
page 7
page 8
page 9-10
page 11
page 12-13
page 14-15
page 16
page 17
page 18
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5
Control Structures
• An algorithm is “a limited and ordered set of well-defined rules for
solving a problem” (see chapter 2)
a given order
• Three categories of execution order or control structures:
– sequential (all client programs up to now)
– selection (the if statement, this chapter)
– loop (the while statement, see chapter 6)
• Activity diagrams illustrate control structures.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 2
Class Diagram and Two Possible Activity Diagrams for a
Calculator object
read two numbers
read two numbers
Calculator calcus =
new Calculator(number1, number2)
Calculator
Calculator calcus =
new Calculator(number1, number2)
number1
number2
getNumber1
getNumber2
setNumbers
calculateSum
calculateDifference
calculateProduct
calculateQuotient
calcus.calculateSum()
[will not
add the numbers]
calcus.
calculateDifference()
[will add the
numbers]
calcus.
calculateSum()
print the result
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
print the result
Chapter 5, page 3
The Calculator Class
class Calculator {
private double number1;
private double number2;
public double calculateSum() {
return number1 + number2;
}
public double calculateDifference() {
return number1 - number2;
}
public Calculator(double initNumber1,
double initNumber2) {
number1 = initNumber1;
number2 = initNumber2;
}
public double calculateProduct() {
return number1 * number2;
}
public double getNumber1() {
return number1;
}
public double calculateQuotient() {
/* Division by zero gives special results:
* Both numerator and denominator are 0:
* Result: Double.NaN ("not-a-number")
* Only denominator is 0:
* Result: Double.NEGATIVE_INFINITY or
*
Double.POSITIVE_INFINITY.
* Printing these values gives "NaN" and "Infinity".
*/
return number1 / number2;
public double getNumber2() {
return number2;
}
public void setNumbers(double newNumber1,
double newNumber2) {
number1 = newNumber1;
number2 = newNumber2;
}
}
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 4
Client
Program
with
Selection
the selection has to be
formulated as a
yes/no question
import javax.swing.JOptionPane;
class TestCalculator1 {
public static void main(String[] args) {
/* Reading data */
String number1Read = JOptionPane.showInputDialog("First number: ");
String number2Read = JOptionPane.showInputDialog("Second number: ");
double number1 = Double.parseDouble(number1Read);
double number2 = Double.parseDouble(number2Read);
int answer = JOptionPane.showConfirmDialog(null, "Add the numbers? ",
"Calculator", JOptionPane.YES_NO_OPTION);
/* Calculating results */
Calculator calcus = new Calculator(number1, number2);
double calculatedAnswer;
char operator;
if (answer == JOptionPane.YES_OPTION) { // Yes is pressed
calculatedAnswer = calcus.calculateSum();
operator = '+';
} else { // No or Esc is pressed, or the dialogue is closed
calculatedAnswer = calcus.calculateDifference();
operator = '-';
}
/* Printing results */
String result = "Our calculation: " + calcus.getNumber1() + " " +
operator + " " + calcus.getNumber2();
result += "\nThe answer is " + calculatedAnswer;
JOptionPane.showMessageDialog(null, result);
System.exit(0);
}
}
Solve problem 2, page 125.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 5
Blocks Inside Methods
Solve problem 2, pp. 132-133.
calculatedAnswer
calculatedAnswer
result
answer
calcus
number2
• As a recommended
practice, variables
should be declared
near the place they are
used.
• An alternative
calculator program is
shown to the right.
The scope of the
variables is shown.
number1
• Local variables are variables declared inside methods.
• The scope of a local variable is the rest of the block where the variable
is declared.
• A method may contain many blocks inside each other.
• Variables can be declared inside blocks.
public static void main(String[] args) {
….
double number1 = …
double number2 = …
Calculator calcus =….
int answer = JOptionPane…..
String result = …..
if (answer == JOptionPane.YES_OPTION) {
double calculatedAnswer =
calcus.calculateSum();
result += "+" + calcus.getNumber2() +
"\nThe answer is " + calculatedAnswer;
} else {
double calculatedAnswer =
calcus.calculateDifference();
result += "-" + calcus.getNumber2() +
"\nThe answer is " + calculatedAnswer;
}
JOptionPane.showMessageDialog(null, result);
System.exit(0);
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 6
The if Statement has Two Versions
[not (boolean
expression)]
[boolean expression]
NB!
Equality is
written with two
equality signs.
if (boolean expression)
statement1
else
statement2
[boolean expression]
[not (boolean
expression)]
A boolean expression may be a
boolean variable or a comparision,
examples:
a > 10
noOfGirls < noOfBoys
noOfMen == noOfWomen
if (boolean expression)
statement
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 7
Curly Braces and Indents
if (boolean expression)
statement1
else
statement2
•
•
•
•
If statement1 and/or statement2 consist of more than one individual statement,
the statements have to be enclosed in curly braces {}.
Otherwise, it’s not necessary to use curly braces. However, for the sake of
readability, and to decrease the chance of errors, we also recommend using
curly braces if only one individual statement is to be executed and there isn’t
room for it on the same line as if or else.
Example, we have discovered that b should be increased by 1 if a > b:
Starting point:
Correction:
if (a > b)
sum += a;
•
•
Why isn't this "correction" correct?
Do you think the chance to get the code correct is higher if the starting point is
as follows:
– if (a > b) sum += a;
•
if (a > b)
sum += a;
b++;
Discussion / conclusion?
If so, why?
Solve problem 2, page 136.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 8
Nested if and Multiple-Choice Statements
•
•
Example:
if (temperature > 0) {
System.out.println("Degrees above zero.");
} else {
if (temperature == 0) {
System.out.println("Zero degrees.");
} else {
System.out.println("Degrees below
zero.");
} // end of the innermost if-else statement
} // end of the outermost if-else statement
if (temperature > 0) {
System.out.println( "Degrees above zero.");
}
if (temperature == 0) {
System.out.println("Zero degrees.");
}
if (temperature < 0) {
System.out.println("Degrees below zero.");
}
•
A few superfluous tests.
Superfluous tests are removed:
•
Or we could write:
if (temperature > 0) System.out.println("Degrees above zero.");
else if (temperature == 0) System.out.println("Zero degrees");
else System.out.println("Degrees below zero.");
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 9
What's the Difference between
the Following Two Code Segments?
int a = -10;
int b = 20;
if (a > 0) {
if (b > 10) b = 10;
}
else a = 0;
System.out.println(a + " " + b);
a = -10;
b = 20;
if (a > 0)
if (b > 10) b = 10;
else a = 0;
System.out.println(a + " " + b);
If you use multiple if statements inside each other (nested if), and an else block
doesn’t belong to the closest preceding if, it has to be marked with {}.
Solve problem 2, page 144.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 10
Decision Tables
• A grade is computed according to the following decision table:
points
90-100
80-89
70-79
60-69
0-59
grade
A
B
C
D
F
• Problem: Complete the getGrade() method:
class Grade {
private int points;
public Grade(int initPoints) {
points = initPoints;
}
public int getGrade() { // negative value is returned if invalid no. of points
.…fill inn what is missing.....
}
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 11
Boolean Expressions
• A boolean expression has the value true or false.
• The logical-complement operator ! (also called the not-operator) reverses the
expression’s value. !true is false and vice versa.
• Boolean expressions are created using the comparison operators:
< less than
<= less than or equal to
> greater than
>= greater than or equal to
!= not equal to
== equal to
Examples:
number > 10
(price * number) != 100
number1 + number2 == number3 + number4
• More complex expressions are created combining simple boolean expressions
using the following two operators:
&& conditional-and (or only: “and”)
|| conditional-or (or only: “or”)
• See operator summary, table 5.4, page 147.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 12
Calculating a Complex Boolean Expression
a >= 0 && a <= 4 || a >= 10 && a <= 15 || a == 20
true
false
true
false
false
a is equal to 16
false
false
false
false
Solve all problems, pp. 149-150.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 13
Comparing Strings
• The String class offers methods to comparing strings.
• Two strings are given:
String name1 = "Margaret Eliza";
String name2 = "Maya";
• Using the equals() method:
if (name1.equals(name2)) System.out.println("The names are the same.");
else System.out.println("The names are not the same.");
• Printout: The names are not the same.
• Using the compareTo() method:
int result = name1.compareTo(name2);
if (result < 0) System.out.println(name1 + " comes first.");
else if (result > 0) System.out.println(name2 + " comes first.");
else System.out.println("The names are the same.");
• Printout: Margaret Eliza comes first.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 14
Methods for Comparing Strings
• The String class offers the following methods for comparing strings:
–
–
–
–
public int compareTo(String theOtherString)
public boolean equals(Object theOtherObject)
public boolean equalsIgnoreCase(String theOtherString)
public int compareToIgnoreCase(String theOtherString)
• Comparing is according to the Unicode order.
• The compareTo() methods returns a negative value if the string we’re
sending the message to comes before theOtherString in the order, a
positive value if it comes after, and 0 if the strings are equal.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 15
Short-Circuit Evaluation
• Boolean expressions containing the operators && or || are calculated
using short-circuit evaluation.
• The computation is ended as soon as the result is determined.
• If we have an && (”and”) operator between the expressions:
– Continue the evaluation as long as the expressions are true.
– The instant the Java interpreter encounters the first expression which
evaluates to false, the compound expression as a whole will be false, and
it can terminate the computation.
• If we have an || (”or”) operator between the expressions:
– Continue the evaluation as long as the expressions are false.
– The instant one of them is true, the Java interpreter can stop, because then
the whole expression is true.
• An example:
– if (number >= 0 && Math.sqrt(number) < limit) ....
• In this example, the order of the comparisons cannot be swapped. If we
do so, we risk trying to compute the square root of a negative number.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 16
String text = JOptionPane.showInputDialog("Which place? ");
int place = Integer.parseInt(text);
switch (place) {
case 1:
JOptionPane.showMessageDialog(null, "Gold!");
If each instance in a multiplebreak;
case 2:
choice statement corresponds
JOptionPane.showMessageDialog(null, "Silver!");
to a specific numerical value
break;
or a character, it may be
case 3:
practical to use the switch
JOptionPane.showMessageDialog(null, "Bronze!");
statement.
break;
See example to the right.
case 4:
All the labels have to
/* falls through */
represent different constant
case 5:
/* falls through */
expressions — in other
case 6:
words, separate values. Thus,
JOptionPane.showMessageDialog(null, "You have points!");
it’s not possible to provide an
break;
interval or a list of values
default:
here.
int luckyNumber = (int) (100 * Math.random() + 1);
Jump out of the switch block
JOptionPane.showMessageDialog(null,
only through "break".
"Thank you for honourable achievement!\n" +
"Your lucky number is: " + luckyNumber);
Solve problem, page 152.
break;
Only to be used in connection with the book "Java the UML}
Way", by Else Lervik and Vegard B. Havdal.
Chapter 5, page 17
The switch
Statement
•
•
•
•
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Comparing Computed Decimal Numerals
•
What is the value of number3 after the following code segment is executed:
double number1 = 1.0e20;
double number2 = number1 + 1.0;
double number3 = number2 - number1;
•
•
Answer: number3 is 0.
Why?
– 1 + 1,0·1020 = 1,00000000000000000001·1020.
– The double data type handles only approx. 15 significant digits.
– The value 1 is loosed if we try to add it to the very large number.
•
•
Never use the operators == and != to compare results from calculations
involving decimal numerals.
Instead, check that the difference between the numbers is less than a given
tolerance (the size of the tolerance should be according to the numbers):
final double tolerance = 0.00001;
if (Math.abs(number1 - number2) < tolerance) {
System.out.println("The numbers are almost the same.");
} else System.out.println("The numbers are different.");
remember using the
absolute value!
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 5, page 18