Boolean Values2
Transcript of Boolean Values2
Boolean Values2
• The program could do decision making by itself, for example,self-driving cars.1
• To do this, Java has the boolean-type flow controls(branching and iteration).
• This type has only two possible values, true and false.
• Note that a boolean value cannot be cast into a value ofanother type, nor can a value of another type be cast into aboolean value. (Why?)
1See https://www.google.com/selfdrivingcar/.2George Boole (1815–1864) is the namesake of the branch of algebra known
as Boolean algebra. See https://en.wikipedia.org/wiki/George_Boole.Zheng-Liang Lu Java Programming 69
Relational Operators3
• Relational operators take two operands and return a booleanvalue.
• Note that the mathematical equality operator is ==, not =.
3See Table 3-1 in YDL, p. 82.Zheng-Liang Lu Java Programming 70
Example
1 ...2 int x = 2;3 System.out.println(x > 1); // Output true.4 System.out.println(x < 1); // Output false.5 System.out.println(x == 1); // Output false.6 System.out.println(x != 1); // Output true.7 System.out.println(1 < x < 3); // Sorry?8 ...
• In Line 7, 1 < x < 3 is syntactically wrong.
• You need to split a complex statement into several basicstatements and joint them by logical operators.
• For example, 1 < x < 3 should be 1 < x && x < 3, where &&presents the AND operator.
Zheng-Liang Lu Java Programming 71
Logical Operators4,5
Operator Name
! NOT
&& AND
|| OR
∧ EXCLUSIVE-OR
• We use XOR to denote the exclusive-or operator.
4See Table 3-2 in YDL, p. 102.5I skip over the bit-wise operators because most of Java programmers do
not use these directly. See https:
//docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html ifnecessary.
Zheng-Liang Lu Java Programming 72
Truth Table
• Let X and Y be two Boolean variables.
• Then the truth table for logical operators is as follows:
X Y !X X&&Y X ‖ Y X ∧YT T F T T F
T F F F T T
F T T F T T
F F T F F F
• It is worth to know that basic instructions of computers, suchas arithmetic operators, are implemented by Boolean logics.6
• For example, 1-bit adder can be implemented by using theXOR operator. (Try!)
6Can you image that the combination of these very basic elements (0, 1,AND, OR, NOT) with jumps produces AlphaGo which beat human beings in2016.
Zheng-Liang Lu Java Programming 73
“Logic is the anatomy of thought.”– John Locke (1632–1704)
“This sentence is false.”
– anonymous“I know that I know nothing.”
– Plato(In Apology, Plato relates that Socrates accounts for his seemingwiser than any other person because he does not imagine that he
knows what he does not know.)
Zheng-Liang Lu Java Programming 74
Arithmetic Compound Assignment Operators7
Operator Operator name
++ Increment (by one)
+= Addition assignment
− = Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
−− Decrement (by one)
7Note that these shorthand operators are not available in languages such asMatlab and R.
Zheng-Liang Lu Java Programming 75
Example
1 ...2 int x = 1;3 System.out.println(x); // Output 1.4
5 x = x + 1;6 System.out.println(x); // Output 2.7
8 x += 2;9 System.out.println(x); // Output 4.
10
11 x++; // Equivalent to x += 1 and x = x + 1.12 System.out.println(x); // Output 5.13 ...
Zheng-Liang Lu Java Programming 76
• The compound assignment operators are also useful for charvalues.8
• For example,
1 ...2 char s = ’a’;3 System.out.println(s); // Output a.4
5 s += 1;6 System.out.println(s); // Output b.7
8 s++;9 System.out.println(s); // Output c.
10 ...
8Contribution by Mr. Edward Wang (Java265) on May 1, 2016.Zheng-Liang Lu Java Programming 77
++x vs. x++
1 ...2 int x = 1;3 int y = ++x;4 System.out.println(y); // Output 2.5 System.out.println(x); // Output 2.6
7 int w = 1;8 int z = w++;9 System.out.println(z); // Output 1.
10 System.out.println(w); // Output 2.11 ...
• The expression ++x first increments the value of x and thenreturns x.
• Instead, x++ first returns the value of x and then incrementsitself.
• We will use these notations very often.
Zheng-Liang Lu Java Programming 78
Operator Precedence9
9See Table3-10 in YDL, p. 116.Zheng-Liang Lu Java Programming 79
Using Parentheses
• Parentheses are used in expressions to change the naturalorder of precedence among the operators.
• One always evaluates the expression inside of parentheses first.
Zheng-Liang Lu Java Programming 80
Scanner Objects
• It is not convenient to modify the source code and recompileit for a different radius.
• Reading from the console enables the program to receive aninput from the user.
• A Scanner object provides some input methods, say the inputreceived from the keyboard or the files.
• Java uses System.in to refer to the standard input device, bydefault, the keyboard.
Zheng-Liang Lu Java Programming 81
Example: Reading Input From Console
1 import java.util.Scanner;2 ...3 // Create Scanner object to receive data from keyboard.4 Scanner input = new Scanner(System.in);5
6 // INPUT7 System.out.println("Enter r?");8 // Assign an integer from the keyboard to r.9 int r = input.nextInt();
10
11 // ALGORITHM12 double A = r * r * 3.14;13
14 // OUTPUT15 System.out.println(A);16 input.close(); // Cleanup: reclaim the resource.17 ...
Zheng-Liang Lu Java Programming 82
• Line 4 is to create a Scanner object as an agent between thekeyboard and your program, by using the new operator.
• It is worthy to note that all objects are dynamically createdand resided in the heap of memory. (See the figure in the nextpage.)
• To manipulate this object, its memory address is thenassigned to the variable input, which is allocated in the stackof memory.
• Then input is called a reference to the Scanner object.10
• From this, the memory contains human data and alsoreferences (i.e., memory addresses).
10If you have programming experience in C/C++, then this reference issimilar to the concept of pointers.
Zheng-Liang Lu Java Programming 83
Simplified Memory Model
Zheng-Liang Lu Java Programming 84
Methods Provided by Scanner11
11See Table 2-1 in YDL, p. 38.Zheng-Liang Lu Java Programming 85
Example: Body Mass Index (BMI)
Write a program which takes user name, height (in cm),weight (in kgw) as input, and then outputs the user nameattached with his/her BMI, which is
BMI =weight (kgw)
height2(m2).
• Be careful about unit conversion!
Zheng-Liang Lu Java Programming 86
1 ...2 Scanner input = new Scanner(System.in);3
4 // INPUT5 System.out.println("Enter your name?");6 String name = input.nextLine();7
8 System.out.println("Enter your height (cm)?");9 double height = input.nextDouble();
10
11 System.out.println("Enter your weight (kgw)?");12 double weight = input.nextDouble();13
14 // ALGORITHM15 double bmi = 10000 * weight / height / height;16
17 // OUTPUT: name (bmi)18 System.out.println(name + " (" + bmi + ")");19 ...
Zheng-Liang Lu Java Programming 87
Exercise: Two Simple Descriptive Statistics
Write a program which takes 3 numbers as user input, andcalculates the average with the standard deviation.
• Note that the standard deviation of these three is given by√∑3i=1(xi − x)2
3,
where x =(∑3
i=1 xi
)/ 3.
• Two of Math methods are listed below:12
• Math.pow(double x , double y) for xy .• Math.sqrt(double x) for
√x .
12Seehttps://docs.oracle.com/javase/tutorial/java/data/beyondmath.html
Zheng-Liang Lu Java Programming 88
1 ...2 // INPUT3 Scanner input = new Scanner(System.in);4 System.out.println("a = ?");5 double a = input.nextDouble();6 System.out.println("b = ?");7 double b = input.nextDouble();8 System.out.println("c = ?");9 double c = input.nextDouble();
10 input.close();11
12 // ALGORITHM13 double mean = (a + b + c) / 3;14 double std = Math.sqrt((Math.pow(a − mean, 2) +15 Math.pow(b − mean, 2) +16 Math.pow(c − mean, 2)) / 3);17
18 // OUTPUT19 System.out.println("Mean = " + mean);20 System.out.println("Std = " + std);21 ...
Zheng-Liang Lu Java Programming 89
1 class Lecture3 {2
3 "Flow Controls: Selection"4
5 }6
7 // Keywords:8 if, else, switch, case, default, break
Zheng-Liang Lu Java Programming 90
Flow Controls
• We proceed to introduce the building blocks of algorithms asfollows.
• First, most of statements are executed in order.
• A program can handle with multiple situations if thebranching (selection) rules are known.
• Moreover, the program can repeat actions if necessary.
• For example, remember how to find the maximum in the inputlist?
Zheng-Liang Lu Java Programming 91
Representation for Branching
• Conditional statements by if-else.
• Conditional statements by switch-case-break-default.
• Conditional operators.
Zheng-Liang Lu Java Programming 92
Branching Statements by if
• The syntax is simple, shown below.
1 ...2 if (/* Condition: a boolean expression */) {3 // Selection body: conditional statements.4 }5 ...
• If the condition is evaluated true, then the conditionalstatements will be executed once.
• If false, then the selection body will be ignored (or we say thatthe program jumps to Line 5).
• Note that the braces can be omitted if the body contains onlysingle statement.
Zheng-Liang Lu Java Programming 93
Zheng-Liang Lu Java Programming 94
Example: Circle Area (Revisited)
Write a program which receives a positive number as thecircle radius and outputs the resulting area.
1 ...2 if (r > 0) {3 double A = r * r * 3.14;4 System.out.println(A);5 }6 ...
• What if the false case?
Zheng-Liang Lu Java Programming 95
The if-else Statements
1 ...2 if (/* Condition: a boolean expression */) {3 // Body for the true case.4 } else {5 // Body for the false case.6 }7 ...
Zheng-Liang Lu Java Programming 96
Example: Circle Area (Revisited)
• Now add a conditional statement for the false case.
1 ...2 if (r > 0) {3 double A = r * r * 3.14;4 System.out.println(A);5 } else {6 System.out.println("Not a circle.");7 }8 ...
Zheng-Liang Lu Java Programming 97
Nested Conditional Statements by Example
• Write a program to convert percentage grades to letter grades.
1 ...2 if (score >= 90)3 System.out.println("A");4 else {5 if (score >= 80)6 System.out.println("B");7 else {8 if (score >= 70)9 System.out.println("C");
10 else {11 if (score >= 60)12 System.out.println("D");13 else14 System.out.println("F");15 }16 }17 }18 ...
Zheng-Liang Lu Java Programming 98
Multiple Branches
1 ...2 if (score >= 90)3 System.out.println("A");4 else if (score >= 80)5 System.out.println("B");6 else if (score >= 70)7 System.out.println("C");8 else if (score >= 60)9 System.out.println("D");
10 else11 System.out.println("F");12 ...
• Easier to read!
• We should avoid deep indentation.
Zheng-Liang Lu Java Programming 99
• The alternative to the previous program looks like:
1 ...2 if (score >= 90 && score <= 100)3 System.out.println("A");4 else if (score >= 80 && score < 90)5 System.out.println("B");6 else if (score >= 70 && score < 80)7 ...8 ...
• However, the order of conditions may be relevant. (Why?)
• The performance may degrade due to the order of conditions.(Why?)
Zheng-Liang Lu Java Programming 100
Common Bugs
1 ...2 if (r > 0);3 double A = r * r * 3.14;4 System.out.println(A);5 ...
• Don’t add a semicolon to the condition (in Line 2).• If you do so in Line 2, this statement is not effective (useless).
• Multiple conditional statements should be grouped by braces.
Zheng-Liang Lu Java Programming 101
Example with Uncertainty
Write a program which first shows a math question, say sumof two random integers ranging from 0 to 9, and asks theuser to type an answer.
• For example, the program shows 2 + 5 =?
• If the user types 7, then the program reports “Correct.”
• Otherwise, the program reports “Wrong answer. The correctanswer is 7.”
• You may use Math.random() for a random value between 0.0and 1.0, excluding themselves.
Zheng-Liang Lu Java Programming 102
Digression: Random Number Generation (RNG)13
• Math.random() produces numbers only between 0.0 and 1.0,exclusive.
• To generate any integer ranging 0 to 9, we could do
(int) (Math.random() × 10),
because there are 10 possible states: 0, 1, 2,. . . , 9.
• In general, you could generate any integer between L and Uby using
(int) (Math.random() × (U − L + 1)) + L. (Why?)
13Seehttps://en.wikipedia.org/wiki/Pseudorandom_number_generator.
Zheng-Liang Lu Java Programming 103
1 ...2 // (1) Generate two random integers.3 int x = (int) (Math.random() * 10);4 int y = (int) (Math.random() * 10);5
6 // (2) Display the math question.7 System.out.println(x + " + " + y + " = ?");8
9 // (3) Ask the user to type his/her answer.10 Scanner input = new Scanner(System.in);11 int z = input.nextInt();12 input.close();13
14 // (4) Judge the input.15 if (z == x + y) {16 System.out.println("Correct.");17 } else {18 System.out.println("Wrong.");19 System.out.println("It is " + (x + y) + ".");20 }21 ...
• Can you extend this program for all arithmetic operators(+−×÷)?
Zheng-Liang Lu Java Programming 104
“Exploring the unknown requires tolerating uncertainty.”
– Brian Greene
“I can live with doubt, and uncertainty, and not knowing.I think it is much more interesting to live not knowing thanhave answers which might be wrong.”
– Richard Feynman
Zheng-Liang Lu Java Programming 105
Exercise
Write a program which outputs the maximum value in 3 ran-dom integers ranging from −50 to 50.
• Recall the first algorithm example in our class.
Zheng-Liang Lu Java Programming 106
1 ...2 int x = (int) (Math.random() * 101) − 50;3 int y = (int) (Math.random() * 101) − 50;4 int z = (int) (Math.random() * 101) − 50;5
6 int max = x;7 if (y > max) max = y;8 if (z > max) max = z;9 System.out.println("max = " + max);
10 ...
• This program is limited by the number of data.
• To develop a reusable solution, we need arrays and loops.
Zheng-Liang Lu Java Programming 107
The switch-case-break-default Statements
1 ...2 switch (target) {3 case v1:4 // Conditional statements.5 break; // Leaving (jump to Line 16).6 case v2:7 .8 .9 .
10 case vk:11 // Conditional statements.12 break; // Leaving (jump to Line 16).13 default:14 // Default statements.15 }16 ...
Zheng-Liang Lu Java Programming 108
• The structure is convenient for finite and discrete conditions.
• The variable target must be a value of char, byte, short, int,or String type.
• The type of v1, . . ., and vk must be identical to target.
• A break statement may be needed to leave the construct.14
• The default case is used to perform default actions when noneof cases matches target.• This acts like the else statements.
14If not, there will be a fall-through behavior.Zheng-Liang Lu Java Programming 109
Example
1 ...2 // We define the traffic lights as follows:3 // RED: 04 // YELLOW: 15 // GREEN: 26
7 int trafficLight = (int) (Math.random() * 3);8
9 switch (trafficLight) {10 case 0:11 System.out.println("Stop!!!");12 break;13 case 1:14 System.out.println("Slow down!!");15 break;16 case 2:17 System.out.println("Go!");18 }19 ...
Zheng-Liang Lu Java Programming 110
Conditional Operators by Example
1 ...2 if (num1 > num2)3 max = num1;4 else5 max = num2;6
7 // The above statement is equivalent to the following:8 max = num1 > num2 ? num1 : num2;9 ...
• If num1 > num2, then do max = num1 .
• Instead, do max = num2 .
Zheng-Liang Lu Java Programming 111
“We must all face the choice between what is right andwhat is easy.”
– Prof. Albus Dumbledore,Harry Potter and the Goblet of Fire, J.K. Rowling
“To be or not to be, that is the question.”
– Prince Hamlet, Hamlet, William Shakespeare
Zheng-Liang Lu Java Programming 112
1 class Lecture4 {2
3 "Flow Controls: Loops"4
5 }6
7 // Keywords:8 while, do, for, break, continue
Zheng-Liang Lu Java Programming 113
Essence of Loops15
A loop can be used to repeat statements without writing thesimilar statements.
• For example, output “Hello, Java.” for 100 times.
1 ...2 System.out.println("Hello, Java.");3 System.out.println("Hello, Java.");4 .5 . // Copy and paste for 97 times.6 .7 System.out.println("Hello, Java.");8 ...
15You may try https:
//www.google.com/doodles/celebrating-50-years-of-kids-coding.Zheng-Liang Lu Java Programming 114
1 ...2 int cnt = 0;3 while (cnt < 100) {4 System.out.println("Hello, Java.");5 cnt++;6 }7 ...
• This is a toy example to show the power of loops.
• In practice, any routine which repeats couples of times16 canbe done by folding them into a loop.
16I prefer to call these routines “patterns.”Zheng-Liang Lu Java Programming 115
成也迴圈,敗也迴圈
• Loops provide substantial computational power.
• Loops bring an efficient way of programming.• Loops could consume a lot of time.
• We will introduce the analysis of algorithms soon.
Zheng-Liang Lu Java Programming 116
The while Loops
A while loop executes statements repeatedly while the con-dition is true.
1 ...2 while (/* Condition: a boolean expression */) {3 // Loop body.4 }5 ...
• If the condition is evaluated true, execute the loop body onceand re-check the condition.
• The loop no longer proceeds as soon as the condition isevaluated false.
Zheng-Liang Lu Java Programming 117
Zheng-Liang Lu Java Programming 118