else - Courses Given

Download Report

Transcript else - Courses Given

Syllabus (1)
Week
1
2
Chapters
Introduction to the course, basic java language
programming concepts:
Primitive Data Types and Operations
Methods, Control
Statements,
Arrays
Methods,
Control
Statements,
Arrays
1, 2
4, 3, 5
3
Object Oriented Programming: Objects and Classes
6
4
Data Member, Member Method, Static and final members.
Constructor
6
5
Visibility Modifiers, Acessors, and Mutators
6
6
Inheritance, Object Class
8
7
Review + Array of Objects, Some handy Java Classes;
Arrays, String, StringBuffer, StringTokenizer, Vector
7
8
MIDTERM
Syllabus (2)
9
Array of Objects, Some handy Java Classes; Arrays, String, 7
StringBuffer, StringTokenizer, Vector
10
Concrete class, Abstract Class, Interface
9
11
Polymorphism
8
12
Error Handling, Exception Classes and Custom Java
Exceptions
15
13
GUI Programming, event driven programming, components 11,
and containers, AWT (Abstract Window Toolkit), swing
12,
13
14
GUI Programming, event driven programming, components 11,
and containers, AWT (Abstract Window Toolkit), swing
12,
13
15
GUI Programming, Applet
16
Review
17
FINAL
14
Chapter 4 Methods

Introducing Methods
– Benefits of methods, Declaring Methods, and Calling Methods

Passing Parameters
– Pass by Value

Overloading Methods
– Ambiguous Invocation

Scope of Local Variables

Method Abstraction

The Math Class

Case Studies

Recursion (Optional)
Introducing Methods
A method is a
collection of
statements that are
grouped together
to perform an
operation.
Method Structure
Introducing Methods, cont.
•parameter profile refers to the
type, order, and number of the
parameters of a method.
•method signature is the
combination of the method name and
the parameter profiles.
•The parameters defined in the
method header are known as formal
parameters.
•When a method is invoked, its
Declaring Methods
public static int max(int num1,
int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
Calling Methods
Example 4.1 Testing the max method
This program demonstrates calling a method
max to return the largest of the int values
TestMax
Run
Calling Methods, cont.
pass the value of i
pass the value of j
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
return result;
}
Calling Methods, cont.
Space required for the
max method
result: 5
num2: 2
num1: 5
Space required for the
main method
k:
j: 2
i: 5
The main method
is invoked.
Space required for the
main method
k:
j: 2
i: 5
Space required for the
main method
k: 5
j: 2
i: 5
The max method is
invoked.
The max method is
finished and the return
value is sent to k.
Stack is empty
The main method
is finished.
CAUTION
A return statement is required for a nonvoid
method. The following method is logically
correct, but it has a compilation error, because the
Java compiler thinks it possible that this method
does not return any value.
public static int xMethod(int n) {
if (n > 0) return 1;
else if (n == 0) return 0;
else if (n < 0) return –1;
}
To fix this problem, delete if (n<0) in the code.
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Pass by Value
Example 4.2 Testing Pass by value
This program demonstrates passing values
to the methods.
TestPassByValue
Run
Pass by Value, cont.
The values of num1 and num2 are
passed to n1 and n2. Executing swap
does not affect num1 and num2.
Space required for the
swap method
temp:
n2: 2
n1: 1
Space required for the
main method
num2: 2
num1: 1
The main method
is invoked
Space required for the
main method
num2: 2
num1: 1
The swap method
is invoked
Space required for the
main method
num2: 2
num1: 1
The swap method
is finished
Stack is empty
The main method
is finished
Overloading Methods
Example 4.3 Overloading the max Method
public static double max(double num1, double
num2) {
if (num1 > num2)
return num1;
else
return num2;
}
TestMethodOverloading
Run
Ambiguous Invocation
Sometimes there may be two or more
possible matches for an invocation of a
method, but the compiler cannot determine
the most specific match. This is referred to
as ambiguous invocation. Ambiguous
invocation is a compilation error.
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Scope of Local Variables
A local variable: a variable defined inside a
method.
Scope: the part of the program where the
variable can be referenced.
The scope of a local variable starts from its
declaration and continues to the end of the
block that contains the variable. A local
variable must be declared before it can be
used.
Scope of Local Variables, cont.
You can declare a local variable with the
same name multiple times in different nonnesting blocks in a method, but you cannot
declare a local variable twice in nested
blocks.
Scope of Local Variables, cont.
It is fine to declare i in two
non-nesting blocks
public static void method1() {
int x = 1;
int y = 1;
It is wrong to declare i in two
two nesting blocks
public static void method2() {
int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i;
}
for (int i = 1; i < 10; i++) {
y += i;
}
}
for (int i = 1; i < 10; i++) {
sum += i;
}
}
Scope of Local Variables, cont.
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
}
Scope of Local Variables, cont.
// With no errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
Method Abstraction
You can think of the method body as a black
box that contains the detailed implementation
for the method.
Optional return
value
Optional Input
Method Signature
Method body
Black Box
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
The Math Class
 Class
constants:
– PI
–E
 Class
methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods
Trigonometric Methods
 sin(double
a)
 cos(double
a)
 tan(double
a)
 acos(double
a)
 asin(double
a)
 atan(double
a)
Exponent Methods

exp(double a)
Returns e raised to the power of a.

log(double a)
Returns the natural logarithm of a.

pow(double a, double b)
Returns a raised to the power of b.

sqrt(double a)
Returns the square root of a.
Rounding Methods

double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a double
value.

double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.

double rint(double x)
x is rounded to its nearest integer. If x is equally close to two integers,
the even one is returned as a double.

int round(float x)
Return (int)Math.floor(x+0.5).

long round(double x)
Return (long)Math.floor(x+0.5).
min, max, abs, and random
 max(a,
b)and min(a, b)
Returns the maximum or minimum of two
parameters.
 abs(a)
Returns the absolute value of the parameter.
 random()
Returns a random double value
in the range [0.0, 1.0).
Example 4.4 Computing Taxes
with Methods
Example 3.1, “Computing Taxes,” uses if statements to
check the filing status and computes the tax based on the
filing status. Simplify Example 3.1 using methods. Each
filing status has six brackets.
The code for computing taxes is nearly same for each filing
status except that each filing status has different bracket
ranges. For example, the single filer status has six brackets
[0, 6000], (6000, 27950], (27950, 67700], (67700,
141250], (141250, 307050], (307050, ), and the married
file jointly status has six brackets [0, 12000], (12000,
46700], (46700, 112850], (112850, 171950], (171950,
307050], (307050, ).
Example 4.4 Computing Taxes
with Methods
The first bracket of each filing status is taxed at
10%, the second 15%, the third 27%, the fourth
30%, the fifth 35%, and the sixth 38.6%. So you
can write a method with the brackets as arguments
to compute the tax for the filing status. The
signature of the method is:
public static double computeTax(double income,
int r1, int r2, int r3, int r4, int r5)
ComputeTaxWithMethod
Run
Example 4.5 Computing Mean
and Standard Deviation
Generate 10 random numbers and compute the
mean and standard deviation
n
mean 
 xi
n
n
i 1
n
deviation 
ComputeMeanDeviation
x
i 1
2
i

(  xi ) 2
i 1
n
n 1
Run
Example 4.6 Obtaining Random
Characters
Write the methods for generating random
characters. The program uses these methods to
generate 175 random characters between ‘!' and ‘~'
and displays 25 characters per line. To find out the
characters between ‘!' and ‘~', see Appendix B,
“The ASCII Character Set.”
RandomCharacter
Run
Example 4.6 Obtaining Random
Characters, cont.
Appendix B: ASCII Character Set
Case Studies
Example 4.7 Displaying Calendars
The program reads in the month and year
and displays the calendar for a given month
of the year.
PrintCalendar
Run
Design Diagram
printCalendar
(main)
printMonth
readInput
getStartDay
printMonthTitle
getTotalNumOfDays
getMonthName
getNumOfDaysInMonth
isLeapYear
printMonthBody
Recursion (Optional)
Example 4.8 Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
Factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1))
= 3 * ( 2 * (1 * factorial(0))) =
3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) = 3 * 2 = 6
ComputeFactorial
Run
Example 4.8 Computing
Factorial, cont.
main method:
factorial(4)
Step 9: factorial(4) returns 24 (4*6)
factorial(4) is called in the main
factorial(4) = 4*factorial(3)
Step 8: factorial(3) returns 6 (3*2)
Step 1: factorial(4) calls factorial(3)
factorial(3) = 3*factorial(2)
Step 7: factorial(2) returns 2 (2*1)
Step 2: factorial(3) calls factorial(2)
factorial(2) = 2*factorial(1)
Step 6: factorial(1) returns 1 (1*1)
Step 3: factorial(2) calls factorial(1)
factorial(1) = 1*factorial(0)
Step 5: factorial(0) returns 1
Step 4: factorial(1) calls factorial(0)
factorial(0) = 1
Example 4.8 Computing
Factorial, cont.
Required
5 Space
for factorial(0)
Required
1 Space
for factorial(4)
Required
4 Space
for factorial(1)
Space Required
for factorial(1)
Required
3 Space
for factorial(2)
Space Required
for factorial(2)
Space Required
for factorial(2)
Required
2 Space
for factorial(3)
Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
Required
6 Space
for factorial(1)
Space Required
for factorial(2)
Required
7 Space
for factorial(2)
Space Required
for factorial(3)
Space Required
for factorial(3)
Required
8 Space
for factorial(3)
Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
Required
9 Space
for factorial(4)
Fibonacci Numbers
Example 4.8 Computing Finonacci Numbers
0 1 1 2 3 5 8 13 21 34 55 89…
f0 f1
fib(0) = 0;
fib(1) = 1;
fib(n) = fib(n-1) + fib(n-2); n>=2
fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(1) = (1 + 0)
+fib(1) = 1 + fib(1) = 1 + 1 = 2
Fibonacci Numbers, cont
ComputeFibonacci
Run
Fibonnaci Numbers, cont.
1
fib(4)=
fib(3) + fib(2)
call fib(3)
return fib(3)
2
call fib(2)
fib(3)=
fib(2) + fib(1)
7
return fib(2)
3
fib(2)=
fib(1) + fib(0)
return fib(1)
4
fib(1)=
1
return fib(1)
6
call fib(1)
5
fib(0)=
0
fib(2)=
fib(1) + fib(0)
fib(1)=
1
8
fib(1)=
1
9
fib(0)=
1
Towers of Hanoi
Example 4.10 Solving the Towers of Hanoi
Problem
Solve the towers of Hanoi problem.
TowersOfHanoi
Run
Towers of Hanoi, cont.
A
B
C
A
Step 0: Starting status
A
B
B
C
A
B
Step 3: Move disk 1 from B to C
B
C
Step 5: Move disk 1 from C to A
C
A
Step 2: Move disk 2 from A to C
A
C
Step 4: Move disk 3 from A to B
Step 1: Move disk 1 from A to B
A
B
B
C
Step 6: Move disk 2 from C to B
C
A
B
Step 7: Mve disk 1 from A to B
C
Exercise 4.11 GCD
gcd(2, 3) = 1
gcd(2, 10) = 2
gcd(25, 35) = 5
gcd(205, 301) = 5
gcd(m, n)
Approach 1: Brute-force, start from min(n, m) down to 1,
to check if a number is common divisor for both m and
n, if so, it is the greatest common divisor.
Approach 2: Euclid’s algorithm
Approach 3: Recursive method
Approach 2: Euclid’s algorithm
// Get absolute value of m and n;
t1 = Math.abs(m); t2 = Math.abs(n);
// r is the remainder of t1 divided by t2;
r = t1 % t2;
while (r != 0) {
t1 = t2;
t2 = r;
r = t1 % t2;
}
// When r is 0, t2 is the greatest common divisor between t1 and t2
return t2;
Approach 3: Recursive Method
gcd(m, n) = n if m % n = 0;
gcd(m, n) = gcd(n, m % n); otherwise;
Chapter 3 Control Statements
Selection
Statements
–Using if and if...else
–Nested if Statements
–Using switch Statements
–Conditional Operator
Repetition
Statements
–Looping: while, do-while, and for
–Nested loops
–Using break and continue
Selection Statements

if Statements

switch Statements

Conditional Operators
if Statements
if (booleanExpression) {
statement(s);
}
Example:
if (i > 0 && i < 10) {
System.out.println("i is an " +
"integer between 0 and 10");
}
Caution
Adding a semicolon at the end of an if
clause is a common mistake.
if (radius >= 0);
Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is
not a compilation error or a runtime error,
it is a logic error.
This error often occurs when you use the
next-line block style.
The if...else Statement
if (booleanExpression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
if...else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area for the “
+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
Multiple Alternative if Statements
if (score >= 90)
grade = ‘A’;
else
if (score >= 80)
grade = ‘B’;
else
if (score >= 70)
grade = ‘C’;
else
if (score >= 60)
grade = ‘D’;
else
grade = ‘F’;
if (score >= 90)
grade = ‘A’;
else if (score >= 80)
grade = ‘B’;
else if (score >= 70)
grade = ‘C’;
else if (score >= 60)
grade = ‘D’;
else
grade = ‘F’;
Note
The else clause matches the most recent if
clause in the same block. For example, the
following statement
int i = 1; int j = 2; int k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
is equivalent to
int i = 1; int j = 2; int k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
Note, cont.
Nothing is printed from the preceding
statement. To force the else clause to
match the first if clause, you must
add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
Example 3.1 Computing Taxes
The US federal personal income
tax is calculated based on the
filing status and taxable income.
There are four filing status:
single filers, married filing
jointly, married filing
separately, and head of
household. The tax rates for 2002
are shown in Table 3.1.
Example 3.1 Computing Taxes
Compute Tax
Run
switch Statements
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file
jointly;
break;
case 2: compute taxes for married file
separately;
break;
case 3: compute taxes for head of
household;
break;
default: System.out.println("Errors:
invalid status");
System.exit(0);
switch Statement Flow Chart
status is 0
Compute tax for single filers
break
Compute tax for married file jointly
break
Compute tax for married file separatly
break
Compute tax for head of household
break
status is 1
status is 2
status is 3
default
Default actions
Next Statement
switch Statement Rules
The switch-expression must yield a value
of char, byte, short, or int type and
must always be enclosed in parentheses.
The value1, ..., and valueN must have the
same data type as the value of the
switch-expression. The resulting
statements in the case statement are
executed when the value in the case
statement matches the value of the
switch-expression. (The case statements
are executed in sequential order.)
The keyword break is optional, but it
should be used at the end of each case in
switch Statement Rules, cont.
The default case, which is optional,
can be used to perform actions when
none of the specified cases is true.
The order of the cases (including the
default case) does not matter.
However, it is a good programming
style to follow the logical sequence
of the cases and place the default
case at the end.
Conditional Operator
if (x > 0) y = 1
else y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
Ternary operator
Binary operator
Unary operator
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);
Conditional Operator, cont.
(booleanExp) ? exp1 : exp2
Repetitions
 while

do-while Loops
 for

Loops
Loops
break and continue
while Loop Flow Chart
while (continuation-condition) {
// loop-body;
}
Continuation
condition?
true
Statement(s)
Next
Statement
false
while Loop Flow Chart, cont.
i = 0;
int i = 0;
while (i < 100) {
System.out.println(
"Welcome to Java!");
i++;
}
(i < 100)
false
true
System.out.println("Welcoem to Java!");
i++;
Next
Statement
Example 3.2: Using while Loops
TestWhile.java
TestWhile
Run
Caution
Don’t use floating-point values for
equality checking in a loop control. Since
floating-point values are approximations,
using them could result in imprecise
counter values and inaccurate results. This
example uses int value for data. If a
floating-point type value is used for data,
(data != 0) may be true even though data is
0.
// data should be zero
double data = Math.pow(Math.sqrt(2), 2) - 2;
if (data == 0)
System.out.println("data is zero");
else
do-while Loop
Statement(s)
true
do {
// Loop body;
} while (continuation-condition);
Continue
condition?
false
Next
Statement
for Loops
for (initial-action; loop-continuation-condition;
action-after-each-iteration) {
//loop body;
}
int i = 0;
while (i < 100) {
System.out.println("Welcome to Java!" + i);
i++;
}
Example:
int i;
for (i = 0; i < 100; i++) {
System.out.println("Welcome to Java!" + i);
}
for Loop Flow Chart
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
//loop body;
}
Action-AfterEach-Iteration
Initial-Action
Continuation
condition?
true
Statement(s)
(loop-body)
Next
Statement
false
for Loop Example
int i;
for (i = 0; i<100; i++) {
System.out.println(
"Welcome to Java");
}
i=0
i++
i<100?
false
true
System.out.println(
“Welcom to Java!”);
Next
Statement
for Loop Examples
Examples for using the for loop:

Example 3.3: Using for Loops
TestSum

Run
Example 3.4: Using Nested for Loops
TestMulTable
Run
Which Loop to Use?
The three forms of loop statements, while, do-while, and
for, are expressively equivalent; that is, you can write a
loop in any of these three forms.
I recommend that you use the one that is most intuitive
and comfortable for you. In general, a for loop may be
used if the number of repetitions is known, as, for
example, when you need to print a message 100 times. A
while loop may be used if the number of repetitions is not
known, as in the case of reading the numbers until the
input is 0. A do-while loop can be used to replace a while
loop if the loop body has to be executed before testing the
continuation condition.
Caution
Adding a semicolon at the end of the
for clause before the loop body is a
common mistake, as shown below:
Logic
Error
for (int i=0; i<10; i++);
{
System.out.println("i is " + i);
}
Caution, cont.
Similarly, the following loop is also
wrong:
Logic Error
int i=0;
while (i < 10);
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the
following semicolon is needed to end
the loop.
int i=0;
do {
Correct
System.out.println("i is " + i);
i++;
The break Keyword
Continuation
condition?
true
Statement(s)
break
Statement(s)
Next
Statement
false
The continue Keyword
Continue
condition?
true
Statement(s)
continue
Statement(s)
Next
Statement
false
Using break and continue
Examples for using the break and continue
keywords:

Example 3.5: TestBreak.java
TestBreak

Run
Example 3.6: TestContinue.java
TestContinue
Run
Example 3.7
Finding the Sales Amount
You have just started a sales job in a
department store. Your pay consists of a base
salary and a commission. The base salary is
$5,000. The scheme shown below is used to
determine the commission rate.
Sales Amount
Commission Rate
$0.01–$5,000
8 percent
$5,000.01–$10,000
10 percent
$10,000.01 and above12 percent
Your goal is to earn $30,000 in a year. Write a
program that will find out the minimum amount
of sales you have to
generate in order Run
to make
FindSalesAmount
$30,000.
Example 3.8
Displaying a Pyramid of Numbers
In this example, you will use nested loops to
print the following output:
1
212
32123
4321234
543212345
Your program prints five lines. Each line
consists of three parts. The first part
comprises the spaces before the numbers; the
second part, the leading numbers, such as 3 2 1
PrintPyramid
Run
on line 3; and the last
part, the ending
numbers, such as 2 3 on line 3.
Example 3.9
Displaying Prime Numbers
This example displays the first 50 prime
numbers in five lines, each of which contains
10 numbers. An integer greater than 1 is prime
if its only positive divisor is 1 or itself.
For example, 2, 3, 5, and 7 are prime numbers,
but 4, 6, 8, and 9 are not.
The problem can be broken into the following
tasks:
•For number = 2, 3, 4, 5, 6, ..., test whether
the number is prime.
•Determine whether a given number is prime.
•Count the prime numbers.
PrimeNumber
Run
•Print each prime number, and print 10 numbers
per line.