Scanner Class
It is not convenient to modify the source code and recompile it for a different radius. • Reading from the console enables the program to receive an
input from the user. • Scanner class provides input methods. • Java uses System.in to refer to the standard input device. • By default, the input device is the keyboard.
Zheng-Liang Lu
Java Programming
76 / 125
Example: Reading Input From The Console
Write a program which receives a number as input, and determine the area of the circle. 1 2 3 4 5 6 7 8
import java.util.Scanner; // import a class ... Scanner input = new Scanner(System.in); // create an object ... radius = input.nextDouble(); // return a double to radius ... input.close(); ...
Zheng-Liang Lu
Java Programming
77 / 125
1
import java.util.Scanner;
2 3 4 5 6 7 8 9 10 11 12
public class ComputeAreaWithConsoleInput { public static void main (String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter r? "); double r = input.nextDouble(); double area = r ∗ r ∗ 3.14; System.out.println("area = " + area); input.close(); } }
• In the listing, Line 5 is used to create a Scanner object by the
new operator, and then return its memory address assigned to the variable input. • So the variable input is a reference variable. • We will discuss the objects and reference variables in OO
lectures. Zheng-Liang Lu
Java Programming
78 / 125
Methods Within Scanner Objects1
1
See Table 2-1 in YDL, p. 38. Zheng-Liang Lu
Java Programming
79 / 125
Example: Sample Mean and Sample Standard Deviation Write a program which calculates the sample mean and the sample standard deviation of 3 numbers. • Sample mean of 3 numbers is given by x =
P
3 i=1 xi
/3.
• Also, the sample standard deviation is given by
s S=
P3
i=1 (xi
− x)2
2
.
• You may use these two methods: • Math.pow(double x , double y) for x y √ • Math.sqrt(double x) for x • See more methods within Math class. Zheng-Liang Lu
Java Programming
80 / 125
1
... public static void main (String[] args) { Scanner input = new Scanner(System.in); System.out.println("a = ?"); double a = input.nextDouble(); System.out.println("b = ?"); double b = input.nextDouble(); System.out.println("c = ?"); double c = input.nextDouble();
2 3 4 5 6 7 8 9 10
double mean = (a + b + c) / 3; double std = Math.sqrt((Math.pow(a − mean, 2) + Math.pow(b − mean, 2) + Math.pow(c − mean, 2)) / 2);
11 12 13 14 15
System.out.println("mean = " + mean); System.out.println("std = " + std);
16 17
}
18 19
...
Zheng-Liang Lu
Java Programming
81 / 125
1
class Lecture3 {
2
"Selections"
3 4 5
}
6 7 8 9
/∗ References [1] Ch. 3 in YDL ∗/
Zheng-Liang Lu
Java Programming
82 / 125
Flow Controls
The basic algorithm or program constitutes the following operations: • Sequence: instructions executed in order. • Selection: first check if the condition is satisfied, then
select the next instruction based on boolean values. • Repetition: repeat the execution of a block of
instructions until the criterion is not satisfied.
Zheng-Liang Lu
Java Programming
83 / 125
• Note that these operations are not mutually exclusive. • In most cases, they are involved with each other. • For example, recall how to find the highest score of math quiz
in the class? Zheng-Liang Lu
Java Programming
84 / 125
Selections
Java has several types of selection statements: • one-way if statements • two-way if-else statements • nested if statements • switch-case statements • conditional operators
Zheng-Liang Lu
Java Programming
85 / 125
One-Way if Statements A one-way if statement executes an action if and only if the condition is true.
Zheng-Liang Lu
Java Programming
86 / 125
1 2 3
if (condition) { // selection body }
• The keyword if is followed by the parenthesized condition. • The condition should be a boolean expression or a boolean
value. • It the condition is true, then the statements in the selection
body will be executed once. • If not, then the program won’t enter the selection body. • Note that the braces can be omitted if the block contains a
single statement.
Zheng-Liang Lu
Java Programming
87 / 125
Example
Write a program which receives a nonnegative number as input for the radius of a circle, and determines the area of the circle. 1 2 3 4 5 6
... if (r >= 0) { area = r ∗ r ∗ 3.14; System.out.println("area = " + } ...
area);
• However, the world is not well-defined.
Zheng-Liang Lu
Java Programming
88 / 125
Two-Way if-else Statements
A two-way if-else statement decides which statements to execute based on whether the condition is true or false. 1 2 3 4 5
if (condition) { // selection body 1 } else { // selection body 2 }
Zheng-Liang Lu
Java Programming
89 / 125
Zheng-Liang Lu
Java Programming
90 / 125
Example Write a program which receives a number as input for the radius of a circle. If the number is nonnegative, then determine the area of the circle; otherwise, print “Not a circle.” 1
... Scanner input = new Scanner(System.in); System.out.println("Enter radius: "); double r = input.nextDouble(); double area; if (r >= 0) { area = r ∗ r ∗ 3.14; System.out.println("area = " + area); } else { System.out.println("Not a circle."); } input.close();
2 3 4 5 6 7 8 9 10 11 12
}
13 14
...
Zheng-Liang Lu
Java Programming
91 / 125
Example: Nested if Statements An if statement can be inside another if statement to form a nested if statement. 1
... if (score >= 90) System.out.println("A"); else { if (score >= 80) System.out.println("B"); else { if (score >= 70) System.out.println("C"); else { if (score >= 60) System.out.println("D"); else System.out.println("F"); } } }
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
... Zheng-Liang Lu
Java Programming
92 / 125
Example: Multi-Way if-else 1 2 3 4 5 6 7 8 9 10 11 12
... if ((score >= 90) && (score = 80) && (score < 90)) System.out.println("B"); else if ((score >= 70) && (score < 80)) System.out.println("C"); else if ((score >= 60) && (score < 70)) System.out.println("D"); else System.out.println("F"); ...
• An if-elseif-else statement is a preferred format for multiple
alternatives, in order to avoid deep indentation and makes the program easy to read. • The order of conditions may be relevant. (Why?) • The performance may degrade due to the order of conditions. (Why?) Zheng-Liang Lu
Java Programming
93 / 125
Common Errors in Selection Statements • Fix the two bugs for the following code snippet: 1 2 3 4 5
... if (r > 0); area = r ∗ r ∗ pi; System.out.println("Area = " + area); ...
• Terrible code snippet if the curly braces are ignored, for
example, 1 2 3 4 5 6 7 8 9 10
... int i = 1, j = 2, k = 3; if (i > j) if (i > k) System.out.println("Max = " + i); else if (j > k) System.out.println("Max = " + j); else System.out.println("Max = " + k); ...
Zheng-Liang Lu
Java Programming
94 / 125
Example Generating random numbers Write a program which generates 2 random integers and asks the user to answer the math expression. • For example, the program shows 2 + 5 =? • If the user answers 7, then the program reports “Correct.”
and terminates. • Otherwise, the program reports “Wrong answer. The correct
answer is 7.” for this case. • You may use Math.random() for a random value between 0.0
and 1.0, excluding themselves.
Zheng-Liang Lu
Java Programming
95 / 125
1
... public static void main(String[] args) {
2 3
int x = (int) (Math.random() ∗ 10); // integers 0 ˜ 9 int y = (int) (Math.random() ∗ 10);
4 5 6
System.out.println(x + " + " + y + " =
7
?");
8
Scanner in = new Scanner(System.in); int z = in.nextInt();
9 10 11
if (z == (x + y)) System.out.println("Correct."); else System.out.println("Wrong. The correct answer is " + (x + y) + "."); in.close();
12 13 14 15 16
}
17 18
...
• Can you extend this program to include + − ×÷ in the math
expressions? Zheng-Liang Lu
Java Programming
96 / 125
Exercise
Find Maximum Write a program which finds the maximum value in 3 random integers whose range from 1 to 100. • How many variables do we need? • How to compare? • How to keep the maximum value?
Zheng-Liang Lu
Java Programming
97 / 125
1
... public static void main(String[] args) {
2 3
int x = (int) (Math.random() ∗ 100 + 1); int y = (int) (Math.random() ∗ 100 + 1); int z = (int) (Math.random() ∗ 100 + 1);
4 5 6 7
int max = x; if (y > max) max = y; if (z > max) max = z; System.out.println("max = " + max);
8 9 10 11
}
12 13
...
• In this case, a scalar variable is not convenient. (Why?) • So we need two more elements: arrays and loops.
Zheng-Liang Lu
Java Programming
98 / 125
switch-case Statements A switch-case statements executes statements based on the value of a variable or an expression. 1 2 3 4 5 6 7 8 9 10 11 12 13
switch (target) { case v1: statements; break; case v2: . . case vk: statements; break; default: statements; }
Zheng-Liang Lu
Java Programming
99 / 125
• A switch-case statements is more convenient than an if
statement to simply the code for multiple discrete conditions. • The variable target, always enclosed in parentheses, must yield
a value of char, byte, short, int, or String type. • The value v1 , . . ., and vk must have the same data type as the
variable target. • In each case, a break statement is a must.2 • The default case, which is optional, can be used to perform
actions when none of the specified cases matches target.
2
If not, there will be a fall-through behavior. Zheng-Liang Lu
Java Programming
100 / 125
Example Write a program which picks a day of week randomly. • How many discrete cases? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
... int day = (int) (Math.random() ∗ 7) + 1; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: Zheng-Liang Lu
Java Programming
101 / 125
System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Invalid weekday?");
17 18 19 20 21 22 23 24 25 26
}
27 28
...
• Note that 0, 1, 2, . . . , 6 are preferable instead of 1, 2, 3, . . . , 7.
(Why?) • When we use switch-case statements?
Zheng-Liang Lu
Java Programming
102 / 125
Conditional Operators
A conditional expression evaluates an expression based on the specified condition. 1
booleanExpr ? exprA : exprB;
• If the boolean expression is true, then the result is expr A;
otherwise, expr B.
Zheng-Liang Lu
Java Programming
103 / 125
• For example, 1
... if (num1 > num2) max = num1; else max = num2;
2 3 4 5 6
...
• Alternatively, one can use a conditional expression like this: 1 2 3
... max = (num1 > num2) ? num1 : num2; ...
Zheng-Liang Lu
Java Programming
104 / 125
1
class Lecture4 {
2
"Loops"
3 4 5
}
6 7 8 9
/∗ References [1] Ch. 5 in YDL ∗/
Zheng-Liang Lu
Java Programming
105 / 125
Loops
A loop can be used to make a program execute statements repeatedly without having to code the same statements. • For example, a program outputs “Hello, Java.” for 100 times. 1 2 3 4 5 6
System.out.println("Hello, Java."); System.out.println("Hello, Java."); . . // Copy and paste for 100 times . System.out.println("Hello, Java.");
Zheng-Liang Lu
Java Programming
106 / 125
int cnt = 0; while (cnt < 100) { System.out.println("Hello, Java."); cnt++; }
1 2 3 4 5
• This is a simple example to show the power of loops. • In practice, any routine which repeats couples of times3 can
be done by folding them into a loop.
3
I’d like to call them “patterns.” Zheng-Liang Lu
Java Programming
107 / 125
成也迴圈,敗也迴圈。
• Loops provide significant computation power. • Loops bring an efficient way of programming. • Loops could consume a lot of time.4
4
We will visit the analysis of algorithms in the end of this lecture. Zheng-Liang Lu
Java Programming
108 / 125
while Loops A while loop executes statements repeatedly while the condition is true. 1
... while (condition) { // loop body }
2 3 4 5
...
• The condition is a Boolean expression which controls the
execution of the body. • It is evaluated each time to determine if the loop body is
executed. • If true, the loop body is executed. • Otherwise, the entire loop terminates. Zheng-Liang Lu
Java Programming
109 / 125
Zheng-Liang Lu
Java Programming
110 / 125
Example
Write a program which sums up all integers from 1 to 100. • In math, the question can be:
sum = 1 + 2 + · · · + 100. • But the form is not doable in the machine. • Try computational thinking.5
5
We are familiar with mathematical thinking since we learn math before we learn how to code. Zheng-Liang Lu
Java Programming
111 / 125
• Normally, the computer executes the instructions sequentially.6 • So one needs to decompose the math equation into several
steps, like: int sum sum . . . sum
1 2 3 4 5 6 7
sum = 0; = sum + 1; = sum + 2;
= sum + 100;
• Cons: not efficient, not general (what if sum up to 1010 ?)
6
If we are talking about the parallel computing, then it is a different story. Zheng-Liang Lu
Java Programming
112 / 125
• Using a while loop, the program looks like this: 1
... int sum = 0; int i = 1; while (i