liang,introduction to java programming,revised by dai-kaiyu1 chapter 3 control statements...
Post on 21-Dec-2015
301 views
TRANSCRIPT
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1
Chapter 3 Control Statements
Chapter 1 Introduction to Computers, Programs, and Java
Chapter 2 Primitive Data Types and Operations
Chapter 3 Control Statements
Chapter 5 Arrays
Chapter 4 Methods
Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word
Prerequisites for Part I
选择是艰难的
谁能控制自己的命运?
Liang,Introduction to Java Programming,revised by Dai-kaiyu 2
Objectives• To understand the flow of control in selection and loop statements
(§3.2-3.7).• To use Boolean expressions to control selection statements and loop
statements (§3.2-3.7).• To implement selection control using if and nested if statements
(§3.2).• To implement selection control using switch statements (§3.2).• To write expressions using the conditional operator (§3.2).• To use while, do-while, and for loop statements to control the
repetition of statements (§3.4).• To write nested loops (§3.4).• To know the similarities and differences of three types of loops
(§3.5).• To implement program control with break and continue (§3.6).
Liang,Introduction to Java Programming,revised by Dai-kaiyu3
Algorithms
Algorithm Series of actions in specific order
The actions executed The order in which actions execute
Program control Specifying the order in which actions execute
Control structures help specify this order
Liang,Introduction to Java Programming,revised by Dai-kaiyu4
PseudocodePseudocode
Informal language for developing algorithms Not executed on computers Helps developers “think out” algorithms Normally describes only executable
statementsif student’s grade is greater then or equal to 60
Print " Passed"
if(grade>=60)
System.out.println(“Passed");
Liang,Introduction to Java Programming,revised by Dai-kaiyu5
Control Structures
Sequential execution Program statements execute one after the other
Transfer of control Three control statements can specify order of
statements Sequence structure (built in Java) Selection structure Repetition structure
Flowchart Graphical representation of algorithm
Flowlines indicate order in which actions execute
Liang,Introduction to Java Programming,revised by Dai-kaiyu6
add grade to total total = total + grade;
add 1 to counter counter = counter + 1 ;
Flowcharting Java’s sequence structure.
Flowlines
Action Symbols
Connector Symbols
Liang,Introduction to Java Programming,revised by Dai-kaiyu7
grade >= 60true
false
print “Passed”
Flowcharting the single-selection if structure.
Decision Symbol
Liang,Introduction to Java Programming,revised by Dai-kaiyu8
Selection Statements
if Statements
switch Statements
Conditional Operators
Liang,Introduction to Java Programming,revised by Dai-kaiyu9
Simple if Statements
Boolean Expression
true
Statement(s)
false (radius >= 0)
true
area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area);
false
(A) (B)
if (booleanExpression) { statement(s);}
if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" + “ for the circle of radius " + radius + " is " + area);}
Liang,Introduction to Java Programming,revised by Dai-kaiyu10
Note
if ((i > 0) && (i < 10)) { System.out.println("i is an " + + "integer between 0 and 10"); }
(a)
Equivalent
(b)
if ((i > 0) && (i < 10)) System.out.println("i is an " + + "integer between 0 and 10");
Outer parentheses required Braces can be omitted if the block contains a single statement
Liang,Introduction to Java Programming,revised by Dai-kaiyu11
Caution
Adding a semicolon at the end of an if clause is a common mistake.
if (radius >= 0);
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}logic error. This error often occurs when you use the next-line block style.
Wrong
Liang,Introduction to Java Programming,revised by Dai-kaiyu12
The if...else Statementif (booleanExpression) { statement(s)-for-the-true-case;}else { statement(s)-for-the-false-case;}
Boolean Expression
false true
Statement(s) for the false case Statement(s) for the true case
What if there is no else statement, the difference
Can’t use 0,1
Liang,Introduction to Java Programming,revised by Dai-kaiyu13
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");}
Liang,Introduction to Java Programming,revised by Dai-kaiyu14
Multiple Alternative if Statements
if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';
Equivalent
if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';
better
Liang,Introduction to Java Programming,revised by Dai-kaiyu15
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 The condition is false
Liang,Introduction to Java Programming,revised by Dai-kaiyu16
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 The condition is false
Liang,Introduction to Java Programming,revised by Dai-kaiyu17
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 The condition is true
Liang,Introduction to Java Programming,revised by Dai-kaiyu18
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 grade is C
Liang,Introduction to Java Programming,revised by Dai-kaiyu19
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 Exit the if statement
Liang,Introduction to Java Programming,revised by Dai-kaiyu20
NoteThe else clause matches the most recent if clause in the same block.
int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");
(a)
Equivalent
(b)
int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");
Liang,Introduction to Java Programming,revised by Dai-kaiyu21
Note, cont.To force the else clause to match the first if clause: 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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu22
TIP
if (number % 2 == 0) even = true; else even = false;
(a)
Equivalent boolean even = number % 2 == 0;
(b)
Liang,Introduction to Java Programming,revised by Dai-kaiyu23
CAUTION
if (even == true) System.out.println( "It is even.");
(a)
Equivalent if (even) System.out.println( "It is even.");
(b)
better
if (even = true)
statement;
compare
Liang,Introduction to Java Programming,revised by Dai-kaiyu 24
1 // Fig. 2.20: Comparison.java2 // Compare integers using if structures, relational operators 3 // and equality operators.4 5 // Java extension packages6 import javax.swing.JOptionPane;7 8 public class Comparison {9 10 // main method begins execution of Java application11 public static void main( String args[] )12 {13 String firstNumber; // first string entered by user14 String secondNumber; // second string entered by user15 String result; // a string containing the output16 int number1; // first number to compare17 int number2; // second number to compare18 19 // read first number from user as a string20 firstNumber =21 JOptionPane.showInputDialog( "Enter first integer:" );22 23 // read second number from user as a string24 secondNumber =25 JOptionPane.showInputDialog( "Enter second integer:" );26 27 // convert numbers from type String to type int28 number1 = Integer.parseInt( firstNumber );29 number2 = Integer.parseInt( secondNumber );30 31 // initialize result to empty String32 result = "";33 Can we omit this statement?
Liang,Introduction to Java Programming,revised by Dai-kaiyu 25
34 if ( number1 == number2 )35 result = number1 + " == " + number2;36 37 if ( number1 != number2 )38 result = number1 + " != " + number2;39 40 if ( number1 < number2 )41 result = result + "\n" + number1 + " < " + number2;42 43 if ( number1 > number2 )44 result = result + "\n" + number1 + " > " + number2;45 46 if ( number1 <= number2 )47 result = result + "\n" + number1 + " <= " + number2;48 49 if ( number1 >= number2 )50 result = result + "\n" + number1 + " >= " + number2;51 52 // Display results53 JOptionPane.showMessageDialog(54 null, result, "Comparison Results",55 JOptionPane.INFORMATION_MESSAGE );56 57 System.exit( 0 ); // terminate application58 59 } // end method main60 61 } // end class Comparison
Test for equality, create new string, assign to result.
Notice use of JOptionPane.INFORMATION_MESSAGE
Liang,Introduction to Java Programming,revised by Dai-kaiyu26
lengthy statement split after comma, operator,…,indent
JOptionPane.showMessageDialog( null, result, “Comparison Results W AS ” + “ASASA DA DSA DAS DAS “, JOptionPane.INFORMATION_MESSAGE );
In main method, we always do not put such trivial statements.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 27
Program Output
Liang,Introduction to Java Programming,revised by Dai-kaiyu28
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 statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2002 are shown in Table 3.1.
Liang,Introduction to Java Programming,revised by Dai-kaiyu29
Example 3.1 Computing Taxes, cont.
Compute TaxWithSelectionStatementCompute TaxWithSelectionStatement Run
if (status == 0) { // Compute tax for single filers}else if (status == 1) { // Compute tax for married file jointly}else if (status == 2) { // Compute tax for married file separately}else if (status == 3) { // Compute tax for head of household}else { // Display wrong status}
Computer may think none of the branch will excute. Thus cause errors
Common Error Not initializing before using a variable in method
Liang,Introduction to Java Programming,revised by Dai-kaiyu30
switch Statementsswitch (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);}
Liang,Introduction to Java Programming,revised by Dai-kaiyu31
switch Statement Flow Chart
status is 0 Compute tax for single filers break
Compute tax for married file jointly break status is 1
Compute tax for married file separatly break status is 2
Compute tax for head of household break status is 3
Default actions default
Next Statement
Liang,Introduction to Java Programming,revised by Dai-kaiyu32
switch Statement Rules
switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default;}
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. Note that value1, ..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x.
Liang,Introduction to Java Programming,revised by Dai-kaiyu33
switch Statement Rules
The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.
switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default;}The default case, which is
optional, can be used to perform actions when none of the specified cases matches the switch-expression. The case statements are executed in sequential order, but
the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.
Liang,Introduction to Java Programming,revised by Dai-kaiyu34
Switch 语句的落空
在 switch语句中,你通常在每一种 case情况后都应使用 break语句,否则,第一个相等情况后面所有的语句都会被执行,这种情况叫做落空
TestSwitch.java
下面程序的输出结果是什么
TestSwitch1.java
TestSwitch2.java
TestSwitch3.java
Liang,Introduction to Java Programming,revised by Dai-kaiyu35
Conditional operator (?:) Java’s only ternary operator-takes three operands(Ternary ;Binary ;Unary )
Grammer
Variable = booleanexpression ? expression1 : expression2
If (booleanexpression)
variable = expression1;
else
variable = expression2;
Liang,Introduction to Java Programming,revised by Dai-kaiyu36
Conditional Operator
if (x > 0) y = 1else y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;(booleanExpression) ? expression1 :
expression2
Liang,Introduction to Java Programming,revised by Dai-kaiyu37
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”);
Liang,Introduction to Java Programming,revised by Dai-kaiyu38
Repetitions
while Loops
do-while Loopsfor Loops
break and continue
Liang,Introduction to Java Programming,revised by Dai-kaiyu39
while Loop Flow Chart
while (loop-continuation-condition) {
// loop-body;
Statement(s);
}
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
}
Loop Continuation Condition?
true
Statement(s) (loop body)
false (count < 100)?
true
System.out.println("Welcome to Java!"); count++;
false
(A) (B)
count = 0;
Liang,Introduction to Java Programming,revised by Dai-kaiyu40
Trace while Loop
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Initialize count
Liang,Introduction to Java Programming,revised by Dai-kaiyu41
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is true
Liang,Introduction to Java Programming,revised by Dai-kaiyu42
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
Liang,Introduction to Java Programming,revised by Dai-kaiyu43
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1count is 1 now
Liang,Introduction to Java Programming,revised by Dai-kaiyu44
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is still true since count is 1
Liang,Introduction to Java Programming,revised by Dai-kaiyu45
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
Liang,Introduction to Java Programming,revised by Dai-kaiyu46
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1count is 2 now
Liang,Introduction to Java Programming,revised by Dai-kaiyu47
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is false since count is 2 now
Liang,Introduction to Java Programming,revised by Dai-kaiyu48
Trace while Loop
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
The loop exits. Execute the next statement after the loop.
Avoid infinite loops
Liang,Introduction to Java Programming,revised by Dai-kaiyu49
Example 3.2: Using while Loops
Problem: Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input.
TestWhileTestWhile Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu50
Caution
Don’t use floating-point values for equality checking in a loop control.
// data should be zerodouble data = Math.pow(Math.sqrt(2), 2) - 2; if (data == 0) System.out.println("data is zero");else System.out.println("data is not zero");
Demo FloatNotPrecise.java
Liang,Introduction to Java Programming,revised by Dai-kaiyu51
Formulating Algorithms with Top-Down, Stepwise Refinement (Sentinel-Controlled Repetition)
Sentinel value Used to indicated the end of data entry Also called a signal value, flag value
Average2.java has indefinite repetition Indefinite repetition: the number of repetitions is not
known before the loop begins executing. User enters sentinel value (-1) to end repetition
Liang,Introduction to Java Programming,revised by Dai-kaiyu52
Initialize total to zeroInitialize counter to zero
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel Add this grade into the running totalAdd one to the grade counterInput the next grade (possibly the sentinel)
If the counter is not equal to zeroSet the average to the total divided by the counterPrint the average
elsePrint “No grades were entered”
Pseudocode algorithm that uses sentinel-controlled repetition to solve the class-average problem.
Determine the class average for the quiz
Initialize variables
Input,sum up and count the quiz grades
Calculate and print the class average
Liang,Introduction to Java Programming,revised by Dai-kaiyu 53
Average2.java
1 // Fig. 4.9: Average2.java2 // Class average program with sentinel-controlled repetition.3 4 // Java core packages5 import java.text.DecimalFormat;6 7 // Java extension packages8 import javax.swing.JOptionPane;9 10 public class Average2 {11 12 // main method begins execution of Java application13 public static void main( String args[] )14 {15 int gradeCounter, // number of grades entered16 gradeValue, // grade value17 total; // sum of grades18 double average; // average of all grades19 String input; // grade typed by user20 21 // Initialization phase22 total = 0; // clear total23 gradeCounter = 0; // prepare to loop24 25 // Processing phase26 // prompt for input and read grade from user27 input = JOptionPane.showInputDialog(28 "Enter Integer Grade, -1 to Quit:" );29 30 // convert grade from a String to an integer31 gradeValue = Integer.parseInt( input );32
Liang,Introduction to Java Programming,revised by Dai-kaiyu 54
33 while ( gradeValue != -1 ) {34 35 // add gradeValue to total36 total = total + gradeValue;37 38 // add 1 to gradeCounter39 gradeCounter = gradeCounter + 1;40 41 // prompt for input and read grade from user42 input = JOptionPane.showInputDialog(43 "Enter Integer Grade, -1 to Quit:" );44 45 // convert grade from a String to an integer46 gradeValue = Integer.parseInt( input );47 }48 49 // Termination phase50 DecimalFormat twoDigits = new DecimalFormat( "0.00" );51 52 if ( gradeCounter != 0 ) {53 average = (double) total / gradeCounter; 54 55 // display average of exam grades56 JOptionPane.showMessageDialog( null,57 "Class average is " + twoDigits.format( average ),58 "Class Average", JOptionPane.INFORMATION_MESSAGE );59 }60 else61 JOptionPane.showMessageDialog( null,62 "No grades were entered", "Class Average",63 JOptionPane.INFORMATION_MESSAGE );64 65 System.exit( 0 ); // terminate application66
loop until gradeValue equals sentinel value (-1)
Format numbers to nearest hundredth
Return a String
Liang,Introduction to Java Programming,revised by Dai-kaiyu 55
Average2.java67 } // end method main68 69 } // end class Average2
Liang,Introduction to Java Programming,revised by Dai-kaiyu56
double x=70.89771;DecimalFormat y = new DecimalFormat("0.000");System.out.println(y.format( x ));
New operator Creates an object as the program executes by obtaining
enough memory to store an object of the type specified to the right of new
Dynamic memory allocation operator Object of Class String is instantiated automatically
DecimalFormat objects format number
Liang,Introduction to Java Programming,revised by Dai-kaiyu57
average = (double) total / gradeCounter;
Explicit conversionThe value stored in total is still an integerTemporary double version of total created
Promotion(implicit conversion)Cast operators
Parentheses around the name of a data typeFloat-points number are not always 100% precise
Liang,Introduction to Java Programming,revised by Dai-kaiyu58
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
Loop Continuation Condition?
true
Statement(s) (loop body)
false
Liang,Introduction to Java Programming,revised by Dai-kaiyu 59
Components of a typical for structure header.
for Loops
Liang,Introduction to Java Programming,revised by Dai-kaiyu60
for Loopsfor (initial-action; loop-
continuation-condition; action-after-each-iteration) {
// loop body; Statement(s);}
int i;for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); }
Loop Continuation Condition?
true
Statement(s) (loop body)
false
(A)
Action-After-Each-Iteration
Intial-Action
(i < 100)?
true
System.out.println( "Welcome to Java");
false
(B)
i++
i = 0
Can be any statement
Liang,Introduction to Java Programming,revised by Dai-kaiyu61
Trace for Loop
int i;for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); }
Initialize count
Liang,Introduction to Java Programming,revised by Dai-kaiyu62
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); }
Execute initializeri is now 0
Liang,Introduction to Java Programming,revised by Dai-kaiyu63
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); }
(i < 2) is true since i is 0
Liang,Introduction to Java Programming,revised by Dai-kaiyu64
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Print Welcome to Java
Liang,Introduction to Java Programming,revised by Dai-kaiyu65
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Execute adjustment statement i now is 1
Liang,Introduction to Java Programming,revised by Dai-kaiyu66
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
(i < 2) is still true since i is 1
Liang,Introduction to Java Programming,revised by Dai-kaiyu67
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Print Welcome to Java
Liang,Introduction to Java Programming,revised by Dai-kaiyu68
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Execute adjustment statement i now is 2
Liang,Introduction to Java Programming,revised by Dai-kaiyu69
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
(i < 2) is false since i is 2
Liang,Introduction to Java Programming,revised by Dai-kaiyu70
Trace for Loop, cont.
int i;for (i= 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Exit the loop. Execute the next statement after the loop
Control variable’s scope: i can’t be used after the body of the structure,if variable i is defined inside the for structure
Three parts of the for structure can be omitted, but the semicolon can’t
What if here is 2
Liang,Introduction to Java Programming,revised by Dai-kaiyu71
NoteThe initial-action in a for loop can be a list of zero or more comma-separated expressions.
The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something}
Liang,Introduction to Java Programming,revised by Dai-kaiyu72
NoteIf the loop-continuation-condition in a for loop is omitted, it is implicitly true.
for ( ; ; ) { // Do something } (a)
Equivalent while (true) { // Do something }
(b)
(b) Is recommended to avoid confusion
Liang,Introduction to Java Programming,revised by Dai-kaiyu73
Example 3.3 Using for Loops
Problem: Write a program that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.
TestSumTestSum Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu74
Example 3.4 Displaying the Multiplication Table
Problem: Write a program that uses nested for loops to print a multiplication table.
TestMultiplicationTableTestMultiplicationTable
Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu75
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.
for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; }
(A)
Equivalent
(B)
initial-action; while (loop-continuation-condition) { // Loop body; action-after-each-iteration; }
while (loop-continuation-condition) { // Loop body }
(A)
Equivalent
(B)
for ( ; loop-continuation-condition; ) { // Loop body }
Liang,Introduction to Java Programming,revised by Dai-kaiyu76
Recommendationsuse 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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu77
Caution
Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below:
for (int i=0; i<10; i++);
{
System.out.println("i is " + i);
}
Logic Error
Liang,Introduction to Java Programming,revised by Dai-kaiyu78
Caution, cont.Similarly, the following loop is also wrong: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 { System.out.println("i is " + i); i++;} while (i<10);
Logic Error
Correct
Liang,Introduction to Java Programming,revised by Dai-kaiyu79
Statements break and continue
break/continue Alter flow of control
break statement Causes immediate exit from control structure
Used in while, for, do/while or switch statements
continue statement Skips remaining statements in loop body Proceeds to next iteration
Used in while, for or do/while statements
Liang,Introduction to Java Programming,revised by Dai-kaiyu80
Using the Keywords break and continue
Liang,Introduction to Java Programming,revised by Dai-kaiyu81
The continue Keyword
Liang,Introduction to Java Programming,revised by Dai-kaiyu82
Using break and continue
Examples for using the break and continue keywords:
Example 3.5: TestBreak.java
Example 3.6: TestContinue.java
TestBreakTestBreak
TestContinueTestContinue
Run
Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu83
Labeled break and continue Statements
Every statement in Java can have an optional label
Labeled block Set of statements enclosed by {} Preceded by a label
Labeled break statement Exit from nested control structures Proceeds to end of specified labeled block
Labeled continue statement Skips remaining statements in nested-loop body Proceeds to beginning of specified labeled block
Liang,Introduction to Java Programming,revised by Dai-kaiyu 84
1 // Fig. 5.13: BreakLabelTest.java2 // Using the break statement with a label3 4 // Java extension packages5 import javax.swing.JOptionPane;6 7 public class BreakLabelTest {8 9 // main method begins execution of Java application10 public static void main( String args[] )11 {12 String output = "";13 14 stop: { // labeled block15 16 // count 10 rows17 for ( int row = 1; row <= 10; row++ ) {18 19 // count 5 columns20 for ( int column = 1; column <= 5 ; column++ ) {21 22 // if row is 5, jump to end of "stop" block23 if ( row == 5 )24 break stop; // jump to end of stop block25 26 output += "* ";27 28 } // end inner for structure29 30 output += "\n";31 32 } // end outer for structure33 34 // the following line is skipped35 output += "\nLoops terminated normally";
Loop 10 times
stop is the labeled block
Exit to line 37 (next slide)
Nested loop 5 times
Liang,Introduction to Java Programming,revised by Dai-kaiyu 85
36 37 } // end labeled block38 39 JOptionPane.showMessageDialog(40 null, output,"Testing break with a label",41 JOptionPane.INFORMATION_MESSAGE );42 43 System.exit( 0 ); // terminate application44 45 } // end method main46 47 } // end class BreakLabelTest
Liang,Introduction to Java Programming,revised by Dai-kaiyu 86
1 // Fig. 5.14: ContinueLabelTest.java2 // Using the continue statement with a label3 4 // Java extension packages5 import javax.swing.JOptionPane;6 7 public class ContinueLabelTest {8 9 // main method begins execution of Java application10 public static void main( String args[] )11 {12 String output = "";13 14 nextRow: // target label of continue statement15 16 // count 5 rows17 for ( int row = 1; row <= 5; row++ ) {18 output += "\n";19 20 // count 10 columns per row21 for ( int column = 1; column <= 10; column++ ) {22 23 // if column greater than row, start next row24 if ( column > row )25 continue nextRow; // next iteration of26 // labeled loop27 28 output += "* ";29 30 } // end inner for structure31 32 } // end outer for structure33
nextRow is the labeled block
Loop 5 times
Nested loop 10 times
continue to line 14 (nextRow)
Liang,Introduction to Java Programming,revised by Dai-kaiyu 87
34 JOptionPane.showMessageDialog(35 null, output,"Testing continue with a label",36 JOptionPane.INFORMATION_MESSAGE );37 38 System.exit( 0 ); // terminate application39 40 } // end method main41 42 } // end class ContinueLabelTest
Liang,Introduction to Java Programming,revised by Dai-kaiyu88
Example 3.7 Finding the Greatest Common Divisor
Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor.
GreatestCommonDivisorGreatestCommonDivisor RunRun
Liang,Introduction to Java Programming,revised by Dai-kaiyu89
Example 3.8 Finding the Sales Amount
Problem: 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 above 12 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 to make $25,000.
FindSalesAmountFindSalesAmount RunRun
Liang,Introduction to Java Programming,revised by Dai-kaiyu90
Example 3.9 Displaying a Pyramid of Numbers
Problem: Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid. For example, if the input integer is 12, the output is shown below.
PrintPyramidPrintPyramid RunRun
(numberOfLines-row)*3
Three parts
Liang,Introduction to Java Programming,revised by Dai-kaiyu91
Example 3.10 Displaying Prime Numbers
Problem: Write a program that 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.
Solution: 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.•Print each prime number, and print 10 numbers per line.
PrimeNumberPrimeNumber RunRun
Liang,Introduction to Java Programming,revised by Dai-kaiyu92
QUIZ
Identify and correct the errors in each of the following. a. if ( age >= 65 ); System.out.println( "Age greater than or equal to 65" ); else System.out.println( "Age is less than 65 )"; b. int x = 1, total;
while ( x <= 10 ) { total += x;
++x; }a. While ( x <= 100 ) total += x;
++x; b. while ( y > 0 ) {
System.out.println( y );++y;
Liang,Introduction to Java Programming,revised by Dai-kaiyu93
Answer a. if ( age >= 65 ); System.out.println( "Age greater than or equal to 65" ); else System.out.println( "Age is less than 65 )"; b. int x = 1, total;
while ( x <= 10 ) { total += x;
++x; }c. While ( x <= 100 ) total += x;
++x; d. int y = 5; while ( y > 0 ) {
System.out.println( y );++y;
a.Semicolon at the end of the if condition should be removed. The closing double quote of the second System.out.println should be inside of the closing parenthesis.
b. The variable total should be initialized to zero.
d. The ++ operator should be changed to --. The closing curly brace for the while loop is missing.
c. The W in While should be lowercase. The two statements should be enclosed in curly braces to properly group them into the body of the while; otherwise the loop will be an infinite loop
Liang,Introduction to Java Programming,revised by Dai-kaiyu94
Find the error in each of the following. [Note: There may be more than one error.]a.For ( x = 100, x >= 1, x++ ) System.out.println( x );
b.The following code should print whether integer value is odd or even:switch ( value % 2 ) { case 0: System.out.println( "Even integer" ); case 1: System.out.println( "Odd integer" );}
c.The following code should output the odd integers from 19 to 1:for ( x = 19; x >= 1; x += 2 ) System.out.println( x );
d.The following code should output the even integers from 2 to 100:counter = 2;do { System.out.println( counter ); counter += 2;} While ( counter < 100 );
Liang,Introduction to Java Programming,revised by Dai-kaiyu95
Find the error in each of the following. [Note: There may be more than one error.]a.For ( x = 100, x >= 1, x++ ) System.out.println( x );
b.The following code should print whether integer value is odd or even:switch ( value % 2 ) { case 0: System.out.println( "Even integer" ); case 1: System.out.println( "Odd integer" );}
c.The following code should output the odd integers from 19 to 1:for ( x = 19; x >= 1; x += 2 ) System.out.println( x );
d.The following code should output the even integers from 2 to 100:counter = 2;do { System.out.println( counter ); counter += 2;} While ( counter < 100 );
The F in for should be lowercase. Semicolons should be used in the for header instead of commas. ++ should be --
A break statement should be placed in case 0
+= should be -=
The W in While should be lowercase. < should be <=