Chapter 3 Control Statements

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4: Selections.
Advertisements

Control Structures Corresponds with Chapters 3 and 4.
 2002 Prentice Hall. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
1 LOOPS. 2 Repetitions while Loops do-while Loops for Loops break and continue.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 5 Control Statements.
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Chapter 4 Loops Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Control Statements.
Chapter 3 Control Statements F Selection Statements –Using if and if...else –Nested if Statements –Using switch Statements –Conditional Operator F Repetition.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 4 Loops.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 3 Selections.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 5 Control Statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 5 Loops.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 4 Loops Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 5 Loops.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Loops 1. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved while Loop Flow.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Introduction to Control Statements JavaScript – Part 3 George Mason University June 3, 2010.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if / else Selection Structure 4.7.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
1 Chapter 5 Control Statements. 2 Objectives F To understand the flow of control in selection and loop statements. F To use Boolean expressions to control.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,
Introduction to Control Statements IT108 George Mason University.
Chapter 3 Selections Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved
Chapter 4: Looping Structures LECTURER : MRS ROHANI HASSAN
Chapter 3 Control Statements
Selections Java.
Chapter 4 Loops DDC 2133 Programming II.
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4 Control structures and Loops
Chapter 5 Control Statements
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 3 Control Statements
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 4 - Control Structures: Part 1
Chapter 4: Loops and Iteration
Presentation transcript:

Chapter 3 Control Statements 选择是艰难的 谁能控制自己的命运? Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Pseudocode Pseudocode Informal language for developing algorithms Not executed on computers Helps developers “think out” algorithms Normally describes only executable statements if 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Decision Symbol true grade >= 60 print “Passed” false Flowcharting the single-selection if structure. Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Selection Statements if Statements switch Statements Conditional Operators Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Simple if Statements if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" + “ for the circle of radius " + radius + " is " + area); } if (booleanExpression) { statement(s); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Note Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu The if...else Statement Can’t use 0,1 if (booleanExpression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; What if there is no else statement, the difference Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Multiple Alternative if Statements better Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace if-else statement Suppose score is 70.0 The condition is false 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'; Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace if-else statement Suppose score is 70.0 The condition is false 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'; Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace if-else statement Suppose score is 70.0 The condition is true 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'; Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace if-else statement Suppose score is 70.0 grade is C 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'; Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace if-else statement Suppose score is 70.0 Exit the if 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'; Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Note The else clause matches the most recent if clause in the same block. Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu TIP Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu CAUTION better if (even = true) statement; compare Liang,Introduction to Java Programming,revised by Dai-kaiyu

Can we omit this statement? 1 // Fig. 2.20: Comparison.java 2 // Compare integers using if structures, relational operators 3 // and equality operators. 4 5 // Java extension packages 6 import javax.swing.JOptionPane; 7 8 public class Comparison { 9 10 // main method begins execution of Java application 11 public static void main( String args[] ) 12 { 13 String firstNumber; // first string entered by user 14 String secondNumber; // second string entered by user 15 String result; // a string containing the output 16 int number1; // first number to compare 17 int number2; // second number to compare 18 19 // read first number from user as a string 20 firstNumber = 21 JOptionPane.showInputDialog( "Enter first integer:" ); 22 23 // read second number from user as a string 24 secondNumber = 25 JOptionPane.showInputDialog( "Enter second integer:" ); 26 27 // convert numbers from type String to type int 28 number1 = Integer.parseInt( firstNumber ); 29 number2 = Integer.parseInt( secondNumber ); 30 31 // initialize result to empty String 32 result = ""; 33 Can we omit this statement? Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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 results 53 JOptionPane.showMessageDialog( 54 null, result, "Comparison Results", 55 JOptionPane.INFORMATION_MESSAGE ); 56 57 System.exit( 0 ); // terminate application 58 59 } // end method main 60 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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

Liang,Introduction to Java Programming,revised by Dai-kaiyu Program Output Liang,Introduction to Java Programming,revised by Dai-kaiyu

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-kaiyu

Example 3.1 Computing Taxes, cont. 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 Compute TaxWithSelectionStatement Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; case 2: compute taxes for married file separately; case 3: compute taxes for head of household; default: System.out.println("Errors: invalid status"); System.exit(0); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

switch Statement Flow Chart Liang,Introduction to Java Programming,revised by Dai-kaiyu

switch Statement Rules The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; … case valueN: statement(s)N; default: statement(s)-for-default; } 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-kaiyu

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; … case valueN: statement(s)N; 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Switch 语句的落空 下面程序的输出结果是什么 TestSwitch.java 在switch语句中,你通常在每一种case情况后都应使用break语句,否则,第一个相等情况后面所有的语句都会被执行,这种情况叫做落空 TestSwitch1.java TestSwitch2.java TestSwitch3.java Liang,Introduction to Java Programming,revised by Dai-kaiyu

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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Conditional Operator if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; (booleanExpression) ? expression1 : expression2 Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Repetitions while Loops do-while Loops for Loops break and continue Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu while Loop Flow Chart int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; } while (loop-continuation-condition) { // loop-body; Statement(s); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace while Loop Initialize count int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace while Loop, cont. (count < 2) is true int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace while Loop, cont. Print Welcome to Java int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace while Loop, cont. Increase count by 1 count is 1 now int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace while Loop, cont. int count = 0; while (count < 2) { (count < 2) is still true since count is 1 int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace while Loop, cont. Print Welcome to Java int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace while Loop, cont. Increase count by 1 count is 2 now int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace while Loop, cont. int count = 0; while (count < 2) { (count < 2) is false since count is 2 now int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace while Loop int count = 0; while (count < 2) { The loop exits. Execute the next statement after the loop. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Avoid infinite loops Liang,Introduction to Java Programming,revised by Dai-kaiyu

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. TestWhile Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Caution Don’t use floating-point values for equality checking in a loop control. // data should be zero double 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Initialize total to zero Initialize 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 total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “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

Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 // Fig. 4.9: Average2.java 2 // Class average program with sentinel-controlled repetition. 3 4 // Java core packages 5 import java.text.DecimalFormat; 6 7 // Java extension packages 8 import javax.swing.JOptionPane; 9 10 public class Average2 { 11 12 // main method begins execution of Java application 13 public static void main( String args[] ) 14 { 15 int gradeCounter, // number of grades entered 16 gradeValue, // grade value 17 total; // sum of grades 18 double average; // average of all grades 19 String input; // grade typed by user 20 21 // Initialization phase 22 total = 0; // clear total 23 gradeCounter = 0; // prepare to loop 24 25 // Processing phase 26 // prompt for input and read grade from user 27 input = JOptionPane.showInputDialog( 28 "Enter Integer Grade, -1 to Quit:" ); 29 30 // convert grade from a String to an integer 31 gradeValue = Integer.parseInt( input ); 32 Average2.java Liang,Introduction to Java Programming,revised by Dai-kaiyu

loop until gradeValue equals sentinel value (-1) 33 while ( gradeValue != -1 ) { 34 35 // add gradeValue to total 36 total = total + gradeValue; 37 38 // add 1 to gradeCounter 39 gradeCounter = gradeCounter + 1; 40 41 // prompt for input and read grade from user 42 input = JOptionPane.showInputDialog( 43 "Enter Integer Grade, -1 to Quit:" ); 44 45 // convert grade from a String to an integer 46 gradeValue = Integer.parseInt( input ); 47 } 48 49 // Termination phase 50 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 51 52 if ( gradeCounter != 0 ) { 53 average = (double) total / gradeCounter; 54 55 // display average of exam grades 56 JOptionPane.showMessageDialog( null, 57 "Class average is " + twoDigits.format( average ), 58 "Class Average", JOptionPane.INFORMATION_MESSAGE ); 59 } 60 else 61 JOptionPane.showMessageDialog( null, 62 "No grades were entered", "Class Average", 63 JOptionPane.INFORMATION_MESSAGE ); 64 65 System.exit( 0 ); // terminate application 66 loop until gradeValue equals sentinel value (-1) Format numbers to nearest hundredth Return a String Liang,Introduction to Java Programming,revised by Dai-kaiyu

67 } // end method main 68 69 } // end class Average2 Average2.java Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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 70.8957170.898 70.8970.890 Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu average = (double) total / gradeCounter; Explicit conversion The value stored in total is still an integer Temporary double version of total created Promotion(implicit conversion) Cast operators Parentheses around the name of a data type Float-points number are not always 100% precise Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition); Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu for Loops Components of a typical for structure header. Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Can be any statement for Loops for (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!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace for Loop Initialize count int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace for Loop, cont. Execute initializer i is now 0 int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace for Loop, cont. (i < 2) is true since i is 0 int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace for Loop, cont. Print Welcome to Java int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { Execute adjustment statement i now is 1 int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace for Loop, cont. (i < 2) is still true since i is 1 int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace for Loop, cont. Print Welcome to Java int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { Execute adjustment statement i now is 2 int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Trace for Loop, cont. (i < 2) is false since i is 2 int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu

Trace for Loop, cont. int i; for (i= 0; i < 2; i++) { Exit the loop. Execute the next statement after the loop int i; for (i= 0; i < 2; i++) { System.out.println("Welcome to Java!"); } What if here is 2 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 Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Note The 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-kaiyu

(b) Is recommended to avoid confusion Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true. (b) Is recommended to avoid confusion Liang,Introduction to Java Programming,revised by Dai-kaiyu

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. TestSum Liang,Introduction to Java Programming,revised by Dai-kaiyu

Example 3.4 Displaying the Multiplication Table Problem: Write a program that uses nested for loops to print a multiplication table. TestMultiplicationTable Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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. Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Recommendations 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. Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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. do { } while (i<10); Logic Error Correct Liang,Introduction to Java Programming,revised by Dai-kaiyu

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-kaiyu

Using the Keywords break and continue Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu The continue Keyword Liang,Introduction to Java Programming,revised by Dai-kaiyu

Using break and continue Examples for using the break and continue keywords: Example 3.5: TestBreak.java TestBreak Example 3.6: TestContinue.java TestContinue Liang,Introduction to Java Programming,revised by Dai-kaiyu

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

stop is the labeled block 1 // Fig. 5.13: BreakLabelTest.java 2 // Using the break statement with a label 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 public class BreakLabelTest { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 String output = ""; 13 14 stop: { // labeled block 15 16 // count 10 rows 17 for ( int row = 1; row <= 10; row++ ) { 18 19 // count 5 columns 20 for ( int column = 1; column <= 5 ; column++ ) { 21 22 // if row is 5, jump to end of "stop" block 23 if ( row == 5 ) 24 break stop; // jump to end of stop block 25 26 output += "* "; 27 28 } // end inner for structure 29 30 output += "\n"; 31 32 } // end outer for structure 33 34 // the following line is skipped 35 output += "\nLoops terminated normally"; stop is the labeled block Loop 10 times Nested loop 5 times Exit to line 37 (next slide) Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 36 37 } // end labeled block 38 39 JOptionPane.showMessageDialog( 40 null, output,"Testing break with a label", 41 JOptionPane.INFORMATION_MESSAGE ); 42 43 System.exit( 0 ); // terminate application 44 45 } // end method main 46 47 } // end class BreakLabelTest Liang,Introduction to Java Programming,revised by Dai-kaiyu

nextRow is the labeled block 1 // Fig. 5.14: ContinueLabelTest.java 2 // Using the continue statement with a label 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 public class ContinueLabelTest { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 String output = ""; 13 14 nextRow: // target label of continue statement 15 16 // count 5 rows 17 for ( int row = 1; row <= 5; row++ ) { 18 output += "\n"; 19 20 // count 10 columns per row 21 for ( int column = 1; column <= 10; column++ ) { 22 23 // if column greater than row, start next row 24 if ( column > row ) 25 continue nextRow; // next iteration of 26 // labeled loop 27 28 output += "* "; 29 30 } // end inner for structure 31 32 } // end outer for structure 33 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

Liang,Introduction to Java Programming,revised by Dai-kaiyu 34 JOptionPane.showMessageDialog( 35 null, output,"Testing continue with a label", 36 JOptionPane.INFORMATION_MESSAGE ); 37 38 System.exit( 0 ); // terminate application 39 40 } // end method main 41 42 } // end class ContinueLabelTest Liang,Introduction to Java Programming,revised by Dai-kaiyu

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. Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2. GreatestCommonDivisor Run Liang,Introduction to Java Programming,revised by Dai-kaiyu

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. FindSalesAmount Run Liang,Introduction to Java Programming,revised by Dai-kaiyu

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. Three parts (numberOfLines-row)*3 PrintPyramid Run Liang,Introduction to Java Programming,revised by Dai-kaiyu

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. PrimeNumber Run Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu QUIZ Identify and correct the errors in each of the following. 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; } While ( x <= 100 ) total += x; ++x; while ( y > 0 ) { System.out.println( y ); ++y; Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu 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. Answer 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; b. The variable total should be initialized to zero. 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 d. The ++ operator should be changed to --. The closing curly brace for the while loop is missing. Liang,Introduction to Java Programming,revised by Dai-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Find the error in each of the following. [Note: There may be more than one error.] For ( x = 100, x >= 1, x++ )   System.out.println( x ); 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" ); } The following code should output the odd integers from 19 to 1: for ( x = 19; x >= 1; x += 2 )   System.out.println( x ); 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-kaiyu

Liang,Introduction to Java Programming,revised by Dai-kaiyu Find the error in each of the following. [Note: There may be more than one error.] For ( x = 100, x >= 1, x++ )   System.out.println( x ); 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" ); } The following code should output the odd integers from 19 to 1: for ( x = 19; x >= 1; x += 2 )   System.out.println( x ); 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 <= Liang,Introduction to Java Programming,revised by Dai-kaiyu