Presentation is loading. Please wait.

Presentation is loading. Please wait.

Part 2 Control Statements.

Similar presentations


Presentation on theme: "Part 2 Control Statements."— Presentation transcript:

1 Part 2 Control Statements

2 OBJECTIVES In this Part you will learn:
To use the if and if else selection statements to choose among alternative actions. To use the while repetition statement to execute statements in a program repeatedly. To use counter-controlled repetition and sentinel-controlled repetition. To use the assignment, increment and decrement operators.

3 Sequence structure activity diagram.
Solid circle represents the activity’s initial state Solid circle surrounded by a hollow circle represents the activity’s final state Sequence structure activity diagram.

4 Control Structures (Cont.)
Selection Statements if statement Single-selection statement if…else statement Double-selection statement switch statement Multiple-selection statement

5 Control Structures (Cont.)
Repetition statements Also known as looping statements Repeatedly performs an action while its loop-continuation condition remains true while statement Performs the actions in its body zero or more times do…while statement Performs the actions in its body one or more times for statement

6 if Single-Selection Statement
if statements Execute an action if the specified condition is true Can be represented by a decision symbol (diamond) in a UML activity diagram Transition arrows out of a decision symbol have guard conditions Workflow follows the transition arrow whose guard condition is true

7 Fig. 4.2 | if single-selection statement UML activity diagram.
Diamonds Decision symbols (explained in section 4.5) Fig. 4.2 | if single-selection statement UML activity diagram.

8 if…else Double-Selection Statement
if…else statement Executes one action if the specified condition is true or a different action if the specified condition is false if else double-selection statement UML activity diagram.

9 Syntax for the if Statement
if ( <boolean expression> ) <then block> else <else block> Boolean Expression if ( testScore < ) JOptionPane.showMessageDialog(null, "You did not pass" ); else JOptionPane.showMessageDialog(null, "You did pass " ); Then Block Else Block

10 Control Flow true false testScore < 70 ?
JOptionPane. showMessageDialog (null, "You did pass"); false JOptionPane. showMessageDialog (null, "You did not pass"); true This shows how the control logic flows. When the test is true, the true block is executed. When the test is false, the else block is executed.

11 Relational Operators < //less than <= //less than or equal to
!= //not equal to > //greater than >= //greater than or equal to testScore < 80 testScore * 2 >= 350 30 < w / (h * h) x + y != 2 * (a + b) 2 * Math.PI * radius <= The list shows six relational operators for comparing values. The result is a boolean value, i.e., either true or false. One very common error in writing programs is mixing up the assignment and equality operators. We frequently make a mistake of writing if (x = 5) ... when we actually wanted to say if (x == 5) ...

12 Decision Making: Equality and Relational Operators
Condition Expression can be either true or false if statement Simple version in this section, more detail later If a condition is true, then the body of the if statement executed Control always resumes after the if statement Conditions in if statements can be formed using equality or relational operators (next slide)

13 Fig. 14 | Equality and relational operators.

14 Syntax for the if Statement
Introduction to OOP with Java 4th Ed, C. Thomas Wu Syntax for the if Statement if ( <boolean expression> ) <then block> else <else block> Boolean Expression if ( testScore < ) JOptionPane.showMessageDialog(null, "You did not pass" ); else JOptionPane.showMessageDialog(null, "You did pass " ); Then Block Else Block © The McGraw-Hill Companies, Inc.

15 Outline (1 of 2) Comparison.java
Test for equality, display result using printf. Compares two numbers using relational operator <.

16 Outline Comparison.java (2 of 2) Program output
Compares two numbers using relational operator >, <= and >=. Comparison.java (2 of 2) Program output

17 Common Programming Error 9
Placing a semicolon immediately after the right parenthesis of the condition in an if statement is normally a logic error.

18 Decision Making: Equality and Relational Operators (Cont.)
Line 6: begins class Comparison declaration Line 12: declares Scanner variable input and assigns it a Scanner that inputs data from the standard input Lines 14-15: declare int variables Lines 17-18: prompt the user to enter the first integer and input the value Lines 20-21: prompt the user to enter the second integer and input the value

19 Decision Making: Equality and Relational Operators (Cont.)
if statement to test for equality using (==) If variables equal (condition true) Line 24 executes If variables not equal, statement skipped No semicolon at the end of if statement Empty statement No task is performed Lines 26-27, 29-30, 32-33, and 38-39 Compare number1 and number2 with the operators !=, <, >, <= and >=, respectively if ( number1 == number2 ) System.out.printf( "%d == %d\n", number1, number2 );

20 Common Programming Error 10
Confusing the equality operator, ==, with the assignment operator, =, can cause a logic error or a syntax error. The equality operator should be read as “is equal to,” and the assignment operator should be read as “gets” or “gets the value of.” To avoid confusion, some people read the equality operator as “double equals” or “equals equals.”

21 Common Programming Error 11
It is a syntax error if the operators ==, !=, >= and <= contain spaces between their symbols, as in = =, ! =, > = and < =, respectively. Common Programming Error 12 Reversing the operators !=, >= and <=, as in =!, => and =<, is a syntax error.

22 Good Programming Practice 8
A lengthy statement can be spread over several lines. If a single statement must be split across lines, choose breaking points that make sense, such as after a comma in a comma-separated list, or after an operator in a lengthy expression. If a statement is split across two or more lines, indent all subsequent lines until the end of the statement.

23 Good Programming Practice 8
Refer to the operator precedence chart (see the complete chart in Appendix A) when writing expressions containing many operators. Confirm that the operations in the expression are performed in the order you expect. If you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order, exactly as you would do in algebraic expressions. Observe that some operators, such as assignment, =, associate from right to left rather than from left to right.

24 Fig. 2.16 | Precedence and associativity of operations discussed.

25 Compound Statements Use braces if the <then> or <else> block has multiple statements. if (testScore < 70) { JOptionPane.showMessageDialog(null, "You did not pass“ ); JOptionPane.showMessageDialog(null, “Try harder next time“ ); } else JOptionPane.showMessageDialog(null, “You did pass“ ); JOptionPane.showMessageDialog(null, “Keep up the good work“ ); Then Block When there are more than one statement in the then or else block, then we put the braces as this example illustrates. Rules for writing the then and else blocks: - Left and right braces are necessary to surround the statements if the then or else block contains multiple statements. - Braces are not necessary if the then or else block contains only one statement. - A semicolon is not necessary after a right brace. Else Block

26 Style Guide Style 1 Style 2 if ( <boolean expression> ) { … }
else { Style 1 if ( <boolean expression> ) { } else Style 2 Here are two most common format styles. In this course, we will use Style 1, mainly because this style is more common among programmers, and it follows the recommended style guide for Java. If you prefer Style 2, then go ahead and use it. Whichever style you choose, be consistent, because consistent look and feel are very important to make your code readable.

27 The if-then Statement if ( <boolean expression> )
<then block> Boolean Expression if ( testScore >= ) JOptionPane.showMessageDialog(null, "You are an honor student"); Then Block Here's the second form of the if statement. We call this form if-then. Notice that the if–then statement is not necessary, because we can write any if–then statement using if–then–else by including no statement in the else block. For instance, the sample if–then statement can be written as if (testScore >= 95) { messageBox.show("You are an honor student"); } else { } In this book, we use if-then statements whenever appropriate.

28 Control Flow of if-then
testScore >= 95? JOptionPane. showMessageDialog (null, "You are an honor student"); true false This shows how the control logic of the if-then statement flows. When the test is true, the true block is executed. When the test is false, the statement that follows this if-then statement is executed.

29 The Nested-if Statement
The then and else block of an if statement can contain any valid statements, including other if statements. An if statement containing another if statement is called a nested-if statement. if (testScore >= 70) { if (studentAge < 10) { System.out.println("You did a great job"); } else { System.out.println("You did pass"); //test score >= 70 } //and age >= 10 } else { //test score < 70 System.out.println("You did not pass"); } It is possible to write if tests in different ways to achieve the same result. For example, the above code can also be expressed as if (testScore >= 70 && studentAge < 10) { messageBox.show("You did a great job"); } else { //either testScore < 70 OR studentAge >= 10 if (testScore >= 70) { messageBox.show("You did pass"); } else { messageBox.show("You did not pass"); }

30 Control Flow of Nested-if Statement
testScore >= 70 ? inner if messageBox.show ("You did not pass"); false true studentAge < 10 ? messageBox.show ("You did pass"); false messageBox.show ("You did a great job"); true This diagram shows the control flow of the example nested-if statement.

31 Writing a Proper if Control
if (num1 < 0) if (num2 < 0) if (num3 < 0) negativeCount = 3; else negativeCount = 2; negativeCount = 1; negativeCount = 0; negativeCount = 0; if (num1 < 0) negativeCount++; if (num2 < 0) if (num3 < 0) The statement negativeCount++; increments the variable by one The two sample if statements illustrate how the same task can be implemented in very different ways. The task is to find out how many of the three numbers are negative. Which one is the better one? The one on the right is the way to do it. The statement negativeCount++; increments the variable by one and, therefore, is equivalent to negativeCount = negativeCount + 1; The double plus operator (++) is called the increment operator, and the double minus operator (--) is the decrement operator (which decrements the variable by one). What is the values of negativeCount when executing the fragment code shown and num1, num2, and num3 values as shown num1 = -2, num2 = -2, num3 = 2 num1 = 2, num2 = -2, num3 = 2 num1 = -2, num2 = -2, num3 =-2 num1 = 2, num2 = 2, num3 = -2 num1 = -2, num2 = -2, num3 = 2

32 if – else if Control Test Score Grade A B C D F 90  score
if (score >= 90) System.out.print("Your grade is A"); else if (score >= 80) System.out.print("Your grade is B"); else if (score >= 70) System.out.print("Your grade is C"); else if (score >= 60) System.out.print("Your grade is D"); else System.out.print("Your grade is F"); Test Score Grade 90  score A 80  score  90 B 70  score  80 C 60  score  70 D score  60 F This is the style we format the nested-if statement that has empty then blocks. We will call such nested-if statements if-else if. If we follow the general rule , the above if-else if will be written as below, but the style shown in the slide is the standard notation. if (score >= 90) System.out.print("Your grade is A"); else if (score >= 80) System.out.print("Your grade is B"); if (score >= 70) System.out.print("Your grade is C"); if (score >= 60) System.out.print("Your grade is D"); messageBox.show("Your grade is F");

33 Matching else Are and different? A B A Both and means… A B B
if (x < y) if (x < z) System.out.print("Hello"); else System.out.print("Good bye"); A if (x < y) { if (x < z) { System.out.print("Hello"); } else { System.out.print("Good bye"); } Both and means… A B if (x < y) if (x < z) System.out.print("Hello"); else System.out.print("Good bye"); B It is important to realize that the indentation alone is not sufficient to determine the nesting of if statements. The compiler will always match the else with the nearest if as this illustration shows. If you want the else to match with the first if, then you have to write if (x < y) { if (x < z) messageBox.show("Hello"); } else messageBox.show("Good bye");

34 Introduce Java’s remaining control structures for, while , do…while
5.1 Introduction

35 Fig. 5.3 | for statement header components.

36 Control-variable name is counter Control-variable initial value is 1
Increment for counter Control-variable name is counter Control-variable initial value is 1 Condition tests for counter’s final value Outline

37 for Repetition Statement (Cont.)
for ( initialization; loopContinuationCondition; increment ) statement; can usually be rewritten as: initialization; while ( loopContinuationCondition ) { statement; increment; } for Repetition Statement (Cont.)

38 Error-Prevention Tip Although the value of the control variable can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle errors.

39 Fig. 5.4 | UML activity diagram for the for statement in Fig. 5.2.
for ( int counter = 1; counter <= 10; counter++ ) System.out.printf( "%d ", counter ); Fig. 5.4 | UML activity diagram for the for statement in Fig. 5.2.

40 Examples Using the for Statement
Varying control variable in for statement Vary control variable from 1 to 100 in increments of 1 for ( int i = 1; i <= 100; i++ ) Vary co ntrol variable from 100 to 1 in increments of –1 for ( int i = 100; i >= 1; i-- ) Vary control variable from 7 to 77 in increments of 7 for ( int i = 7; i <= 77; i += 7 ) Vary control variable from 20 to 2 in decrements of 2 for ( int i = 20; i >= 2; i -= 2 ) Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20 for ( int i = 2; i <= 20; i += 3 ) Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0 for ( int i = 99; i >= 0; i -= 11 ) Examples Using the for Statement

41 increment number by 2 each iteration
Sum.java Line 11 increment number by 2 each iteration Outline

42 Examples Using the for Statement (Cont.)
Initialization and increment expression can be comma-separated lists of expressions for ( int number = 2; number <= 20; number += 2 ) 12 total += number; E.g., lines of Fig. 5.5 can be rewritten as for ( int number = 2; number <= 20; total += number, number += 2 ) ; // empty statement Examples Using the for Statement (Cont.)

43 Java treats floating-points as type double
Second string is right justified and displayed with a field width of 20 Outline

44 Calculate amount with for statement
Use the comma (,) formatting flag to display the amount with a thousands separator Outline

45 Increment and Decrement Operators
Unary increment and decrement operators Unary increment operator (++) adds one to its operand Unary decrement operator (--) subtracts one from its operand Prefix increment (and decrement) operator Changes the value of its operand, then uses the new value of the operand in the expression in which the operation appears Postfix increment (and decrement) operator Uses the current value of its operand in the expression in which the operation appears, then changes the value of the operand  Increment and Decrement Operators

46 Fig. 4.15 | Increment and decrement operators.

47 Increment.java Postincrementing the c variable
Preincrementing the c variable Outline

48 4.11 Compound Assignment Operators
An assignment statement of the form: variable = variable operator expression; where operator is +, -, *, / or % can be written as: variable operator= expression; example: c = c + 3; can be written as c += 3; This statement adds 3 to the value in variable c and stores the result in variable c 4.11  Compound Assignment Operators

49 Fig. 4.14 | Arithmetic compound assignment operators.

50 Common Programming Error 4.9
Attempting to use the increment or decrement operator on an expression other than one to which a value can be assigned is a syntax error. For example, writing ++(x + 1) is a syntax error because (x + 1) is not a variable. Common Programming Error 4.9

51 Fig. 4.17 | Precedence and associativity of the operators discussed so far.

52 while Repetition Statement
while statement Repeats an action while its loop-continuation condition remains true

53 for Repetition Statement (Cont.)
for ( initialization; loopContinuationCondition; increment ) statement; can usually be rewritten as: initialization; while ( loopContinuationCondition ) { statement; increment; } for Repetition Statement (Cont.)

54 Control-variable name is counter Control-variable initial value is 1
Condition tests for counter’s final value Increment for counter Outline WhileCounter.java

55 Calculate.java // Calculate the sum of the integers from 1 to 10 public class Calculate { public static void main( String args[] ) { int sum; int x; x = 1; // initialize x to 1 for counting sum = 0; // initialize sum to 0 for totaling while ( x <= 10 ) // while x is less than or equal to { sum += x; // add x to sum sum = sum + x; x; // increment x } // end while System.out.printf( "The sum is: %d\n", sum ); } // end main } // end class Calculate

56 Q : What is this program calculate f(x) ?
public class Mystery { public static void main( String args[] ) { int y; int x = 1; int total = 0; while ( x <= 10 ) { y = x * x; System.out.println( y ); total += y; x; } // end while System.out.printf( "Total is %d\n", total ); } // end main } // end class Mystery /************************************************************** Mystery.java

57 Fig. 4.4 | while repetition statement UML activity diagram.
Diamonds Decision symbols (explained in section 4.5) Merge symbols (explained in section 4.7) int product = 3; while (product <= 100) product = 3 * product Fig. 4.4 | while repetition statement UML activity diagram.

58 2 Set grade counter to one 3
1 Set total to zero 2 Set grade counter to one 3 4 While grade counter is less than or equal to ten 5 Prompt the user to enter the next grade 6 Input the next grade 7 Add the grade into the total 8 Add one to the grade counter 9 10 Set the class average to the total divided by ten 11 Print the class average Fig. 4.5 | Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.

59 class GradeBook { // display a welcome message to the GradeBook user public void displayMessage() { // getCourseName gets the name of the course System.out.printf( "Welcome to the grade book\n for \n CSC111 \n!\n\n" ); } // end method displayMessage } // end class GradeBook

60 // GradeBookTestExample2. java import java. util
// GradeBookTestExample2.java import java.util.Scanner; // program uses class Scanner public class GradeBookTestExample2 { public static void main( String args[] ) { // determine class average based on 10 grades entered by user int total; // sum of grades entered by user int gradeCounter; // number of the grade to be entered next int grade; // grade value entered by user int average; // average of grades // create GradeBook object myGradeBook GradeBook myGradeBook = new GradeBook(); myGradeBook.displayMessage(); // display welcome message

61 // find average of 10 grades
// create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // initialization phase total = 0; // initialize total gradeCounter = 1; // initialize loop counter // processing phase while ( gradeCounter <= 10 ) // loop 10 times { System.out.print( "Enter grade: " ); // prompt grade = input.nextInt(); // read grade from user total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter by } // end while

62 // termination phase average = total / 10; // integer division yields integer result // display total and average of grades System.out.printf( "\nTotal of all 10 grades is %d\n", total ); System.out.printf( "Class average is %d\n", average ); } // end main } // end class GradeBookTestExample2

63 // Analysis of examination results. import java. util
// Analysis of examination results. import java.util.Scanner; // class uses class Scanner public class AnalysisTestExample1 { public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // initializing variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int studentCounter = 1; // student counter int result; // one exam result (obtains value from user)

64 // process 10 students using counter-controlled loop
while ( studentCounter <= 10 ) { // prompt user for input and obtain value from user System.out.print( "Enter result from 00: 100" ); result = input.nextInt(); // if...else nested in while if ( result >= 60 ) // if result >=60, passes = passes + 1; // increment passes; else // else result is < 60, so failures = failures + 1; // increment failures // increment studentCounter so loop eventually terminates studentCounter = studentCounter + 1; } // end while

65 // termination phase; prepare and display results
System.out.printf( "Passed: %d\nFailed: %d\n", passes, failures ); // determine whether more than 8 students passed if ( passes > 8 ) System.out.println( "Raise Tuition" ); } // end main } // end class AnalysisTest1

66 Intro to OOP with Java, C. Thomas Wu
Defining Your Own Classes and Methods ©The McGraw-Hill Companies, Inc.

67 Standard Input The technique of using System.in to input data is called standard input. We can only input a single byte using System.in directly. To input primitive data values, we use the Scanner class (from Java 5.0). Scanner scanner; scanner = Scanner.create(System.in); int num = scanner.nextInt(); Standard Input

68 Common Scanner Methods:
Method Example nextByte( ) byte b = scanner.nextByte( ); nextDouble( ) double d = scanner.nextDouble( ); nextFloat( ) float f = scanner.nextFloat( ); nextInt( ) int i = scanner.nextInt( ); nextLong( ) long l = scanner.nextLong( ); nextShort( ) short s = scanner.nextShort( ); next() String str = scanner.next(); Common Scanner Methods:

69 A class is the blueprint from which objects are generated
A class is the blueprint from which objects are generated. In other words, if we have six cars we do not need to define a car six times. We will define a car once (in a class) and then generate as many objects as we want from this class blueprint. A class

70

71 UML representation

72

73

74

75 More Examples myWindow . setVisible ( true ) ;
Object Name Name of the object to which we are sending a message. Method Name The name of the message we are sending. Argument The argument we are passing with the message. myWindow setVisible ( true ) ; More Examples account.deposit( ); student.setName(“john”); car1.startEngine( ); This is the Java syntax for seding a message to an object or a class. In this example, we are sending the setVisible method to myWindow with an argument true, so the window indeed becomes visible. If we want to hide it, then we pass the argument false. The name of the message we send to an object or a class must be the same as the method’s name, so we use the phrase “calling an object’s method” and “sending a message to an object” interchangeably. Sending a Message

76 State-of-Memory Diagram
Execution Flow Program Code State-of-Memory Diagram myWindow : JFrame width height title visible Jframe myWindow; myWindow = new JFrame( ); myWindow.width = 300; 300 200 myWindow.height = 200; myWindow.title = “My First Java Program”; Let’s look at the effect of executing these statements to a JFrame object. When we call an object’s method, the object will carry a task, change its state, or both. My First Java … myWindow.visible = true; true The diagram shows only four of the many data members of a JFrame object.

77 State-of-Memory Diagram
Execution Flow State-of-Memory Diagram myWindow Program Code JFrame myWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle (“My First Java Program”); myWindow.setVisible(true); : JFrame width height title visible Jframe myWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle (“My First Java Program”); 300 200 myWindow.setVisible(true); Let’s look at the effect of executing these statements to a JFrame object. When we call an object’s method, the object will carry a task, change its state, or both. The effect of the setSize method is changing the value of width and height. The effect of the setTitle method is changing the title string to the passed argument. And the effect of setVisible is the changing the value of visible to true, and as a result, the appearance of the window on the screen. My First Java … The diagram shows only four of the many data members of a JFrame object. true The effect of the setSize method is changing the value of width and height. The effect of the setTitle method is changing the title string to the passed argument. And the effect of setVisible is the changing the value of visible to true, and as a result, the appearance of the window on the screen.

78 Standard Input The technique of using System.in to input data is called standard input. We can only input a single byte using System.in directly. To input primitive data values, we use the Scanner class (from Java 5.0). Scanner scanner; scanner = Scanner.create(System.in); int num = scanner.nextInt(); Standard Input

79 The Definition of the Bicycle Class
Intro to OOP with Java, C. Thomas Wu class Bicycle { // Data Member public String ownerName; public float price ; public int size ; } The Definition of the Bicycle Class ©The McGraw-Hill Companies, Inc.

80 Intro to OOP with Java, C. Thomas Wu
Once the Bicycle class is defined, we can create multiple instances. Notice how all the instances have their own copy of data members. bike1 bike2 : Bicycle ownerName : Bicycle ownerName Bicycle bike1, bike2; bike1 = new Bicycle( ); bike1.ownerName = "Adam Smith"; “Adam Smith” “Ben Jones” bike2 = new Bicycle( ); bike2.ownerName = "Ben Jones"; Once a class is defined, we can create multiple instances of the class as shown by this example. Notice how all the instances have their own copy of data members. Sample Code Multiple Instances ©The McGraw-Hill Companies, Inc.

81 First Example: Using the Bicycle Class
Intro to OOP with Java, C. Thomas Wu This sample program shows the main class BicycleRegistration is using the Bicycle class. . import java.util.Scanner; // class uses class Scanner class BicycleRegistration { public static void main(String[] args) { Bicycle bike1, bike2; String owner1, owner2; float price1, price2; int size1, size2; // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); bike1 = new Bicycle( ); //Create and assign values to bike1 // prompt user for input and obtain value from user System.out.print( "Enter the owner name" ); bike1.ownerName = input.next(); owner1 = bike1.ownerName; bike2 = new Bicycle( ); //Create and assign values to bike2 // prompt user for input and obtain value from user System.out.print( "Enter the owner name" ); bike2.ownerName = input.next(); owner2 = bike2.ownerName; bike1.ownerName = "Adam Smith"; This sample program shows the main class BicycleRegistration is using the Bicycle class. This Bicycle class is not part of any standard packages. It is something we (or other programmers) have to define ourselves. First Example: Using the Bicycle Class bike2.ownerName = "Ben Jones"; ©The McGraw-Hill Companies, Inc.

82 The Definition of the Bicycle Class
Intro to OOP with Java, C. Thomas Wu // prompt user for input and obtain value from user System.out.print( "Enter the Price of Bike 1" ); bike1.price = input.nextFloat(); price1 = bike1.price; // prompt user for input and obtain value from user System.out.print( "Enter the Size of Bike 1" ); bike1.size = input.nextInt(); size1 = bike1.size; System.out.println(owner1 + " owns a bicycle Its price is“ + bike1.price + “ Its size is “ + bike1.size); System.out.println(owner2 + " also owns a bicycle."); } The Definition of the Bicycle Class ©The McGraw-Hill Companies, Inc.

83 UML representation

84

85 The Program Structure and Source Files
Intro to OOP with Java, C. Thomas Wu The Program Structure and Source Files BicycleRegistration Bicycle BicycleRegistration.java Bicycle.java There are two source files. Each class definition is stored in a separate file. To run the program: 1. javac Bicycle.java (compile) 2. javac BicycleRegistration.java (compile) 3. java BicycleRegistration (run) ©The McGraw-Hill Companies, Inc.

86 switch Multiple-Selection Statement
switch statement Used for multiple selections

87 switch multiple-selection statement UML activity diagram with break statements.

88 Outline GradeBook5.java (1 of 5)

89 GradeBook5.java (2 of 5) Display prompt Loop condition uses grade to determine whether there is more data to input

90 (grade / 10 ) is controlling expression
GradeBook.java (3 of 5) (grade / 10 ) is controlling expression switch statement determines which case label to execute, depending on controlling expression default case for grade less than 60

91 GradeBook.java (4 of 5) Line 91 default case Outline

92 Common Programming Error
Forgetting a break statement when one is needed in a switch is a logic error.

93 Call GradeBook public methods to count grades
GradeBookTest.java (1 of 2) Outline Call GradeBook public methods to count grades

94 Outline GradeBookTest.java (2 of 2) Program output

95 Good Programming Practice
Although each case and the default case in a switch can occur in any order, place the default case last. When the default case is listed last, the break for that case is not required. Some programmers include this break for clarity and symmetry with other cases.

96 switch Multiple-Selection Statement (Cont.)
Expression in each case Constant integral expression Combination of integer constants that evaluates to a constant integer value Character constant E.g., ‘A’, ‘7’ or ‘$’ Constant variable Declared with keyword final

97 switch Multiple-Selection Statement (Cont.)
Expression in each case Constant integral expression Combination of integer constants that evaluates to a constant integer value Character constant E.g., ‘A’, ‘7’ or ‘$’ Constant variable Declared with keyword final

98 break and continue Statements
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

99 Exit for statement (break) when count equals 5
Outline Loop 10 times Exit for statement (break) when count equals 5

100 Skip line 12 and proceed to line 7 when count equals 5
Loop 10 times Skip line 12 and proceed to line 7 when count equals 5

101 Boolean Operators A boolean operator takes boolean values as its operands and returns a boolean value. The three boolean operators are and: && or: || not ! if (temperature >= 65 && distanceToDestination < 2) { System.out.println("Let's walk"); } else { System.out.println("Let's drive"); } The result of relational comparison such as score > 80 is a boolean value. Relational comparisons can be connected by boolean operators &&, ||, or !. The sample boolean expression is true if BOTH relational comparisons are true.

102 Logical Operators Logical operators Java logical operators
Allows for forming more complex conditions Combines simple conditions Java logical operators && (conditional AND) || (conditional OR) & (boolean logical AND) | (boolean logical inclusive OR) ^ (boolean logical exclusive OR) ! (logical NOT)

103 Logical Operators (Cont.)
Conditional AND (&&) Operator Consider the following if statement if ( gender == FEMALE && age >= 65 ) ++seniorFemales; Combined condition is true if and only if both simple conditions are true Combined condition is false if either or both of the simple conditions are false

104 && (conditional AND) operator truth table.

105 Logical Operators (Cont.)
Conditional OR (||) Operator Consider the following if statement if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) System.out.println( “Student grade is A” ); Combined condition is true if either or both of the simple condition are true Combined condition is false if both of the simple conditions are false

106 || (conditional OR) operator truth table.

107 Logical Operators (Cont.)
Short-Circuit Evaluation of Complex Conditions Parts of an expression containing && or || operators are evaluated only until it is known whether the condition is true or false E.g., ( gender == FEMALE ) && ( age >= 65 ) Stops immediately if gender is not equal to FEMALE

108 Common Programming Error
For example, in the expression ( i != 0 ) && ( 10 / i == 2 ) , the second condition must appear after the first condition, or a divide-by-zero error might occur.

109 Logical Operators (Cont.)
Boolean Logical AND (&) Operator Works identically to && Except & always evaluate both operands Boolean Logical OR (|) Operator Works identidally to || Except | always evaluate both operands

110 Logical Operators (Cont.)
Boolean Logical Exclusive OR (^) One of its operands is true and the other is false Evaluates to true Both operands are true or both are false Evaluates to false Logical Negation (!) Operator Unary operator

111 ^ (boolean logical exclusive OR) operator truth table.

112 ! (logical negation, or logical NOT) operator truth table.

113 Outline Conditional AND truth table Conditional OR truth table
Boolean logical AND truth table

114 Outline Boolean logical inclusive OR truth table
Boolean logical exclusive OR truth table Logical negation truth table

115 Outline

116 Mid Term Exam

117 Examples

118

119

120

121 1 from 3

122 2 from 3

123 3 from 3

124

125 Practical training Read and run the following programs given to you :
ComputeGrade.java CreditTest.java LargestTest.java SecDegEq.java Practical training

126 Write a program to process cars, each car has attributes
model : string year : int price : double 1- Write the class Car 2- Write the class TestCar , which has the main method Ask the user to enter number of cars to process input car information model, year, price display the oldest car information display the average price of cars TEST

127 Question : We want to write a Java program that processes Vehicles as shown in the UML diagram. A Vehicle has a type that shows whether the vehicle is a car, a track or a bus. The bus has the attributes power and nbPassengers. The truck has the attributes power and load. The car has the attributes power and isLuxury. When the load of the vehicle is more than 2000kg and less than 3000kg, the vehicle is in the category of the MidSize Truck. When the load is more than 3000kg, the vehicle is in the category of the heavy truck. Write the Vehicle class. Using the class Vehicle, write the class VehicleProcess, that processes the following tasks: Read the required data vehicle. Displays the only required data of the processed vehicle If the entered data is related to a truck, displays its category according to its load.

128 Author: a string representing the author name of the book
Question 2: We want to write a Java program that manages a Bookstore, we create the shown UML class Book containing the following attributes: Author: a string representing the author name of the book Price: the price of the book. PublishedYear: the publishing year of the book Write the class Book Using the class Book, write the class TestBook that processes the following tasks: Read the number of books in the bookStore. Read the information of each book. Display the number of books that were published before year 2000. Display the author name of the book that has the highest price. Book + Author: String + PublishedYear: int + Price: double TestBook + main(String[] args): void

129 The Definition of the Bicycle Class
Intro to OOP with Java, C. Thomas Wu import java.util.Scanner; // class uses class Scanner class Book { // Data Member public String Author; public int PublishedYear ; public double Price ; } The Definition of the Bicycle Class ©The McGraw-Hill Companies, Inc.

130

131

132 First Example: Using the Bicycle Class
Intro to OOP with Java, C. Thomas Wu import java.util.Scanner; // class uses class Scanner class BicycleRegistration { public static void main(String[] args) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int BooksNumber, BooksBefore2000Count = 0 ; double highestPrice = 0.0; String name; // prompt user to Read the number of books in the bookStore System.out.print( "Enter the Number of Books in th store" ); BooksNumber = input.nextInt(); Book Mybook; Mybook = new Book( ); //Create and assign values to Mybook for ( int counter = 1; counter <= BooksNumber; counter++) { System.out.print( "Enter the Author Name of the Book" ); BooksNumber = input.nextInt(); Mybook.Author = input.next(); This sample program shows the main class BicycleRegistration is using the Bicycle class. This Bicycle class is not part of any standard packages. It is something we (or other programmers) have to define ourselves. First Example: Using the Bicycle Class ©The McGraw-Hill Companies, Inc.

133 The Definition of the Bicycle Class
Intro to OOP with Java, C. Thomas Wu System.out.print( "Enter Published Year of the Book" ); Mybook. PublishedYear = input.nextInt(); System.out.print( "Enter Price of the Book" ); Mybook.Price = input.nextDouble(); If (Mybook.PublishedYear < 200 ) BooksBefore2000Count++; If (Mybook.Price > highestPrice) { highestPrice = Mybook.Price ; name = Mybook.Author ;} } // end for // Display the number of books that were published before year 2000. System.out.println( “Number of books were published before year 2000” BooksBefore2000Count ); // Display the author name of the book that has the highest price. System.out.println(“The author name of the book that has the highest price” name ); } // end main } // end class The Definition of the Bicycle Class ©The McGraw-Hill Companies, Inc.

134 Question : Display the output of the following program.
public class Test { public static void main(String[] args) { int a=10, b=15, c=30; double x=9; System.out.println(" Part A: "); x = a/ 2 + b / 2 + x / 2 + b/ 2.0; System.out.println(" first: x = "+ x ); if ( a > b || a -1 != 2 * b && b >= c ) { x = a + c * a + 2; System.out.println(" TRUE: x = " + x ); }else System.out.println(" FALSE: x = " + (a+c * a + 2) ); System.out.println(" FINISH" ); }

135

136

137

138

139 END of Training Lecture

140 Create object and invoke its method.
// GradeBookTestExample3.java // Create GradeBook object and invoke its determineClassAverage method. import java.util.Scanner; // program uses class Scanner class GradeBook { // GradeBook class GradeBook.java (1 of 3)

141 Outline Declare method displayMessage GradeBook.java (2 of 3)
Declare method determineClassAverage Declare and initialize Scanner variable input Declare local int variables total, gradeCounter, grade and average

142 Outline (3 of 3) GradeBook.java
while loop iterates as long as gradeCounter <= 10 GradeBook.java (3 of 3) Increment the counter variable gradeCounter Calculate average grade Display results

143 Outline Create a new GradeBook object GradeBookTestExample3.java
Call GradeBook’s determineClassAverage method

144

145 Create object and invoke its method.
AnalysisTestExample2 // Analysis of examination results. import java.util.Scanner; // class uses class Scanner class Analysis { public void processExamResults() { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // initializing variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int studentCounter = 1; // student counter int result; // one exam result (obtains value from user)

146 // process 10 students using counter-controlled loop
while ( studentCounter <= 10 ) { // prompt user for input and obtain value from user System.out.print( "Enter result " ); result = input.nextInt(); // if...else nested in while if ( result >= 60 ) // if result >60, passes = passes + 1; // increment passes; else // else result is not >=60, so failures = failures + 1; // increment failures // increment studentCounter so loop eventually terminates studentCounter = studentCounter + 1; } // end while

147 // termination phase; prepare and display results
System.out.printf( "Passed: %d\nFailed: %d\n", passes, failures ); // determine whether more than 8 students passed if ( passes > 8 ) System.out.println( "Raise Tuition" ); } // end method processExamResults } // end class Analysis

148 // Test program for class Analysis. public class AnalysisTestExample2 {
public static void main( String args[] ) { Analysis application = new Analysis(); // create Analysis object application.processExamResults(); // call method to process results } // end main } // end class AnalysisTestExample2

149

150 Outline Declare processExamResults’ local variables
while loop iterates as long as studentCounter <= 10

151 Outline (2 of 2) Analysis.java
Determine whether this student passed or failed and increment the appropriate variable Outline Analysis.java (2 of 2) Determine whether more than eight students passed the exam

152 Outline AnalysisTest2.java Create an Analysis object
More than 8 students passed the exam

153 Formulating Algorithms: Sentinel-Controlled Repetition
Also known as indefinite repetition Use a sentinel value (also known as a signal, dummy or flag value) A sentinel value cannot also be a valid input value

154 1 Initialize total to zero 2 Initialize counter to zero 3
4 Prompt the user to enter the first grade 5 Input the first grade (possibly the sentinel) 6 7 While the user has not yet entered the sentinel 8 Add this grade into the running total 9 Add one to the grade counter 10 Prompt the user to enter the next grade 11 Input the next grade (possibly the sentinel) 12 13 If the counter is not equal to zero 14 Set the average to the total divided by the counter 15 Print the average 16 else 17 Print “No grades were entered” Fig. 4.8 | Class-average problem pseudocode algorithm with sentinel-controlled repetition.

155 Outline GradeBook.java (1 of 3)

156 Outline GradeBook.java (2 of 3) Declare method displayMessage
Declare method determineClassAverage Declare and initialize Scanner variable input Declare local int variables total, gradeCounter and grade and double variable average

157 Outline GradeBook.java (3 of 3)
while loop iterates as long as grade != the sentinel value, -1 GradeBook.java (3 of 3) Calculate average grade using (double) to perform explicit conversion Display average grade Display “No grades were entered” message

158 Outline GradeBookTest4.java Create a new GradeBook object
Call GradeBook’s determineClassAverage method

159 do…while Repetition Statement
do…while structure Similar to while structure Tests loop-continuation after performing body of loop i.e., loop body always executes at least once

160 Declares and initializes control variable counter
Outline Declares and initializes control variable counter DoWhileTest.java Line 8 Lines 10-14 Program output Variable counter’s value is displayed before testing counter’s final value

161 Fig. 5.8 | do...while repetition statement UML activity diagram.
System.out.printf( "%d ", counter ); ++counter; } while ( counter <= 10 ); // end do...while Fig. 5.8 | do...while repetition statement UML activity diagram.

162 Good Programming Practice
Always include braces in a do...while statement, even if they are not necessary. This helps eliminate ambiguity between the while statement and a do...while statement containing only one statement.


Download ppt "Part 2 Control Statements."

Similar presentations


Ads by Google