Object Oriented Programming(OOP) Lectures 2 & 3 PDF

Summary

This document provides lecture material on object-oriented programming (OOP) concepts and includes examples of Java programs focusing on simple computations, input/output, and data types.

Full Transcript

7/29/2024 Object Oriented Programming(OOP) Lecture 2 I T 2 0 4 Dr. Belal Abdullah Hezam 1 Liang, Introduction to...

7/29/2024 Object Oriented Programming(OOP) Lecture 2 I T 2 0 4 Dr. Belal Abdullah Hezam 1 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 1 Object Oriented Programming(OOP) Objectives  To write Java programs to perform simple computations.  To obtain input from the console using the Scanner class.  To use identifiers to name variables, constants, methods, and classes.  To use variables to store data.  To program with assignment statements and assignment expressions. I  To use constants to store permanent data. T  To name classes, methods, variables, and constants by following their naming conventions.  To explore Java numeric primitive data types: byte, short, int, long, float, and double. 2  To read a byte, short, int, long, float, or double value from the keyboard. 0  To perform operations using operators +, -, *, /, and %.  To perform exponent operations using Math.pow(a, b). 4  To write and evaluate numeric expressions.  To obtain the current system time using System.currentTimeMillis().  To use augmented assignment operators (§2.13).  To distinguish between postincrement and preincrement and between postdecrement and predecrement.  To cast the value of one type to another type. 2 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 2 1 7/29/2024 Object Oriented Programming(OOP) Introducing Programming with an Example Listing 2.1 Computing the Area of a Circle I This program computes the area of the circle. T 2 0 ComputeArea Note: Clicking the green button displays the source code with interactive animation. You can also run the code in a browser. Internet 4 connection is needed for this button. Run Note: Clicking the blue button runs the code from Windows. If you cannot run the buttons, see IMPORTANT NOTE: If you cannot run the buttons, see liveexample.pearsoncmg.com/slide/javaslidenote.doc. 3 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 3 Object Oriented Programming(OOP) Trace a Program Execution public class ComputeArea { allocate memory for radius public static void main(String[] args) { double radius; radius no value double area; I T // Assign a radius radius = 20; 2 0 // Compute area area = radius * radius * 3.14159; 4 // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 4 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 2 7/29/2024 Object Oriented Programming(OOP) Trace a Program Execution public class ComputeArea { memory public static void main(String[] args) { double radius; radius no value double area; area no value I T // Assign a radius 2 radius = 20; allocate memory for 0 area // Compute area 4 area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 5 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Trace a Program Execution public class ComputeArea { assign 20 to radius public static void main(String[] args) { double radius; radius 20 double area; area no value I T // Assign a radius radius = 20; 2 0 // Compute area 4 area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 6 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 3 7/29/2024 Object Oriented Programming(OOP) Trace a Program Execution public class ComputeArea { memory public static void main(String[] args) { double radius; radius 20 double area; area 1256.636 I // Assign a radius T radius = 20; 2 compute area and assign it to // Compute area variable area 0 area = radius * radius * 3.14159; 4 // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 7 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 7 Object Oriented Programming(OOP) Trace a Program Execution public class ComputeArea { memory public static void main(String[] args) { double radius; radius 20 I double area; area 1256.636 T // Assign a radius 2 radius = 20; 0 // Compute area 4 area = radius * radius * 3.14159; print a message to the console // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 8 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 4 7/29/2024 Object Oriented Programming(OOP) Reading Numbers from the Keyboard Scanner input = new Scanner(System.in); int value = input.nextInt(); I Method Description T nextByte() reads an integer of the byte type. 2 0 nextShort() reads an integer of the short type. 4 nextInt() reads an integer of the int type. nextLong() reads an integer of the long type. nextFloat() reads a number of the float type. nextDouble() reads a number of the double type. 9 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 9 Object Oriented Programming(OOP) Reading Input from the Console 1. Create a Scanner object Scanner input = new Scanner(System.in); I 2. Use the method nextDouble() to obtain to a double value. For T example, 2 System.out.print("Enter a double value: "); 0 Scanner input = new Scanner(System.in); 4 double d = input.nextDouble(); ComputeAreaWithConsoleInput Run ComputeAverage Run 10 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 5 7/29/2024 Object Oriented Programming(OOP) Implicit Import and Explicit Import java.util.* ; // Implicit import I T java.util.Scanner; // Explicit Import 2 0 4 No performance difference 11 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Identifiers  An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($).  An identifier must start with a letter, an underscore (_), or a I dollar sign ($). It cannot start with a digit. T 2  An identifier cannot be a reserved word. (See Appendix A, “Java 0 Keywords,” for a list of reserved words). 4  An identifier cannot be true, false, or null.  An identifier can be of any length. 12 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 6 7/29/2024 Object Oriented Programming(OOP) Variables // Compute the first area radius = 1.0; area = radius * radius * 3.14159; I System.out.println("The area is “ + area + " T for radius "+radius); 2 0 // Compute the second area 4 radius = 2.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius); 13 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to I // be a double variable; T char a; // Declare a to be a 2 // character variable; 0 4 Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; 14 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 7 7/29/2024 Object Oriented Programming(OOP) Declaring and Initializing in One Step  int x = 1; I  double d = 1.4; T 2 0 Named Constants 4 final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3; 15 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Naming Conventions  Choose meaningful and descriptive names.  Variables and method names: – Use lowercase. If the name consists of several words, I concatenate all in one, use lowercase for the first word, and T capitalize the first letter of each subsequent word in the 2 name. For example, the variables radius and area, and 0 the method computeArea. 4 16 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 16 8 7/29/2024 Object Oriented Programming(OOP) Naming Conventions, cont.  Class names: – Capitalize the first letter of each word in the name. For example, the class name ComputeArea. I T  Constants: 2 – Capitalize all letters in constants, and use 0 underscores to connect words. For example, the 4 constant PI and MAX_VALUE 17 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 17 Object Oriented Programming(OOP) Numerical Data Types N am e R an g e S tora g e S ize byte – 2 7 to 2 7 – 1 (-12 8 to 12 7) 8-bit sig n ed short – 2 1 5 to 2 1 5 – 1 (-32 768 to 32 767 ) 16 -b it sig ned I int – 2 3 1 to 2 3 1 – 1 (-21 474 83 64 8 to 214 7 4 83 647 ) 32 -b it sig ned T long – 2 6 3 to 2 6 3 – 1 64 -b it sig ned (i.e., -9 2 2 3 37 20 368 54 77 580 8 to 9 223 3 7 2 03 685 47 758 07 ) 2 0 float N e gative ran ge : -3.4 02 8 23 5E + 3 8 to -1.4E -45 32 -b it IE E E 7 54 P o sitiv e ran g e: 4 1.4 E -4 5 to 3.40 28 2 35 E + 38 double N ega tive ran ge : 64 -b it IE E E 7 54 -1.7 97 6 93 134 86 231 5 7E + 3 08 to -4.9E -3 2 4 P o sitiv e ran g e: 4.9 E -3 2 4 to 1.79 76 931 3 4 86 231 5 7E + 3 08 18 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 9 7/29/2024 Object Oriented Programming(OOP) Reading Numbers from the Keyboard Scanner input = new Scanner(System.in); int value = input.nextInt(); I Method Description T nextByte() reads an integer of the byte type. 2 nextShort() reads an integer of the short type. 0 4 nextInt() reads an integer of the int type. nextLong() reads an integer of the long type. nextFloat() reads a number of the float type. nextDouble() reads a number of the double type. 19 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Numeric Operators Name Meaning Example Result + Addition 34 + 1 35 I T - Subtraction 34.0 – 0.1 33.9 2 * Multiplication 300 * 30 9000 0 4 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2 20 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 20 10 7/29/2024 Object Oriented Programming(OOP) Integer Division +, -, *, /, and % I T 5 / 2 yields an integer 2. 2 0 5.0 / 2 yields a double value 2.5 4 5 % 2 yields 1 (the remainder of the division) 21 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Remainder Operator Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose today is I Saturday and you and your friends are going to meet in 10 days. T What day is in 10 days? You can find that day is Tuesday using the 2 following expression: 0 4 S a t u r d a y i s t h e 6 th d a y i n a w e e k A week has 7 days (6 + 10) % 7 is 2 T h e 2 nd d a y i n a w e e k i s T u e s d a y After 10 days 22 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 22 11 7/29/2024 Object Oriented Programming(OOP) Problem: Displaying Time Write a program that obtains minutes and remaining seconds from seconds. I T 2 0 4 DisplayTime Run 23 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Exponent Operations System.out.println(Math.pow(2, 3)); // Displays 8.0 I System.out.println(Math.pow(4, 0.5)); T // Displays 2.0 2 System.out.println(Math.pow(2.5, 2)); 0 // Displays 6.25 4 System.out.println(Math.pow(2.5, -2)); // Displays 0.16 24 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 12 7/29/2024 Object Oriented Programming(OOP) Arithmetic Expressions 3  4 x 10 ( y  5 )( a  b  c ) 4 9 x   9(  ) 5 x x y I T is translated to 2 0 4 (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) 25 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 25 Object Oriented Programming(OOP) How to Evaluate an Expression Though Java has its own way to evaluate an expression behind the scene, the result of a Java expression and its corresponding arithmetic expression are the same. Therefore, I you can safely apply the arithmetic rule for evaluating a Java T expression. 3 + 4 * 4 + 5 * (4 + 3) - 1 2 (1 ) in sid e p a re n th e s es firs t 3 + 4 * 4 + 5 * 7 – 1 0 (2 ) m u ltip lic atio n 3 + 16 + 5 * 7 – 1 4 3 + 16 + 35 – 1 (3 ) m u ltip lic atio n (4 ) a d d itio n 19 + 35 – 1 (5 ) a d d itio n 54 - 1 (6 ) su b tra ctio n 53 26 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 26 13 7/29/2024 Object Oriented Programming(OOP) Problem: Converting Temperatures Write a program that converts a Fahrenheit degree to Celsius using the formula: I celsius  ( 95 )( fahrenheit  32 ) T 2 0 Note: you have to write 4 celsius = (5.0 / 9) * (fahrenheit – 32) FahrenheitToCelsius Run 27 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Augmented Assignment Operators I T 2 0 4 28 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 28 14 7/29/2024 Object Oriented Programming(OOP) Increment and Decrement Operators I T 2 0 4 29 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 29 Object Oriented Programming(OOP) Increment and Decrement Operators, cont. I int i = 10; S a m e e ffe c t a s int newNum = 10 * i++; int newNum = 10 * i; T i = i + 1; 2 0 4 int i = 10; S a m e e ffe c t a s int newNum = 10 * (++i); i = i + 1; int newNum = 10 * i; 30 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 15 7/29/2024 Object Oriented Programming(OOP) Increment and Decrement Operators, cont. Using increment and decrement operators makes expressions short, but it I also makes them complex and difficult to read. Avoid using these T operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i. 2 0 4 31 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Assignment Expressions and Assignment Statements Prior to Java 2, all the expressions can be used as statements. Since I Java 2, only the following types of expressions can be statements: T 2 variable op= expression; // Where op is +, -, *, /, or % 0 ++variable; 4 variable++; --variable; variable--; 32 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 16 7/29/2024 Object Oriented Programming(OOP) Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: I T 1. If one of the operands is double, the other is converted into 2 double. 0 4 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int. 33 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Type Casting Implicit casting double d = 3; (type widening) Explicit casting I int i = (int)3.0; (type narrowing) T int i = (int)3.9; (Fraction part is truncated) 2 0 What is wrong? int x = 5 / 2.0; 4 range increases byte, short, int, long, float, double 34 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 34 17 7/29/2024 Object Oriented Programming(OOP) Lecture 3 I T 2 0 4 Dr. Belal Abdullah Hezam 35 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 35 Object Oriented Programming(OOP) I Selections T 2 0 4 36 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 18 7/29/2024 Object Oriented Programming(OOP) Objectives  To write Java programs to perform simple computations.  To declare boolean variables and write Boolean expressions using relational operators.  To implement selection control using one-way if statements.  To implement selection control using two-way if-else statements.  To implement selection control using nested if and multi-way if statements. I  To avoid common errors and pitfalls in if statements.  To generate random numbers using the Math.random() method. T  To program using selection statements for a variety of examples (SubtractionQuiz, BMI, ComputeTax). 2  To combine conditions using logical operators (&&, ||, and !). 0  To program using selection statements with combined conditions (LeapYear, Lottery). 4  To implement selection control using switch statements.  To write expressions using the conditional expression (3.14).  To examine the rules governing operator precedence and associativity. 37 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 37 Object Oriented Programming(OOP) The boolean Type and Operators Often in a program you need to compare two values, such as whether i is greater than j. Java provides six comparison operators (also known as relational operators) that can be used to compare two values. The result of the comparison is a Boolean value: true or false. I boolean b = (1 > 2); T 2 Relational Operators 0 Java Mathematics Name Example Result Operator Symbol (radius is 5) 4 < < less than radius < 0 false greater than radius > 0 true >= ≥ greater than or equal to radius >= 0 true == = equal to radius == 0 false != ≠ not equal to radius != 0 true 38 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 19 7/29/2024 Object Oriented Programming(OOP) Problem: A Simple Math Learning Tool This example creates a program to let a first grader practice additions. The program randomly generates two single-digit integers number1 and number2 and displays a question such as “What is 7 + I 9?” to the student. After the student types the answer, the program T displays a message to indicate whether the answer is true or false. 2 0 4 IMPORTANT NOTE: If you cannot run the buttons, see liveexample.pearsoncmg.com/slide/javaslidenote.doc. AdditionQuiz Run 39 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) One-way if Statements System.currentTimeMillis() is a method returns the current time in milliseconds. I T 2 0 4 40 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 20 7/29/2024 Object Oriented Programming(OOP) One-way if Statements if (radius >= 0) { if (boolean-expression) { area = radius * radius * PI; System.out.println("The area" + " for the circle of radius" statement(s); + radius + " is " + area); } } I T 2 0 4 41 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Note if i > 0 { if ( i > 0 ) { S ys te m. ou t.pr intln(" i is po sitive "); Sys tem.out. pr in tl n (" i is p osi ti ve ") ; } } (a) W ron g (b) C orre ct I T i f (i > 0) { if (i > 0) Sys tem.out.pr intln(" i is po sitive " ); Equ ivale nt Sy ste m.out. p rintln ("i i s positiv e"); 2 } 0 (a) (b) 4 42 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 42 21 7/29/2024 Object Oriented Programming(OOP) Simple if Demo Write a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If the number is divisible by 2, print HiEven. I T 2 0 4 SimpleIfDemo Run 43 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 43 Object Oriented Programming(OOP) The Two-way if Statement if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } I if-else Example T 2 if (radius >= 0) { area = radius * radius * 3.14159; 0 System.out.println("The area for the “ 4 + “circle of radius " + radius + " is " + area); } else { System.out.println("Negative input"); } 44 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 44 22 7/29/2024 Object Oriented Programming(OOP) Multiple Alternative if Statements if ( s co r e >= 9 0.0 ) if ( s c or e > = 9 0. 0) S y s te m. o ut. p r in t ( "A ") ; S y s t em. o u t. p r i nt ( " A") ; el s e el s e i f ( s c or e > = 8 0.0) i f (s c o r e > = 80. 0 ) Eq uiv alent S y s t em. o u t. p r i nt ( " B") ; S ys t e m.o u t. pr i n t ( "B " ) ; el s e i f ( s c or e > = 7 0.0) I else S y s t em. o u t. p r i nt ( " C") ; i f ( s c or e > = 7 0. 0 ) el s e i f ( s c or e > = 6 0.0) T S y s t em. o u t. p r i n t( " C " ); S y s t em. o u t. p r i nt ( " D") ; e ls e el s e 2 i f ( sc o r e > = 60.0) S y s t em. o u t. p r i nt ( " F") ; S y st e m. ou t. p r int ( " D" ) ; 0 else This is b etter S y st e m. ou t. p r in t( " F" ) ; 4 (a) (b ) 45 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 45 Object Oriented Programming(OOP) Multi-Way if-else Statements I T 2 0 4 46 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 46 23 7/29/2024 Object Oriented Programming(OOP) Trace if-else statement Suppose score is 70.0 The condition is false if (score >= 90.0) System.out.print("A"); I else if (score >= 80.0) T System.out.print("B"); 2 else if (score >= 70.0) System.out.print("C"); 0 else if (score >= 60.0) 4 System.out.print("D"); else System.out.print("F"); 47 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Trace if-else statement Suppose score is 70.0 The condition is false if (score >= 90.0) I System.out.print("A"); else if (score >= 80.0) T System.out.print("B"); 2 else if (score >= 70.0) 0 System.out.print("C"); 4 else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); 48 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 24 7/29/2024 Object Oriented Programming(OOP) Trace if-else statement Suppose score is 70.0 The condition is true if (score >= 90.0) System.out.print("A"); I else if (score >= 80.0) T System.out.print("B"); 2 else if (score >= 70.0) System.out.print("C"); 0 else if (score >= 60.0) 4 System.out.print("D"); else System.out.print("F"); 49 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Trace if-else statement grade is C Suppose score is 70.0 if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) I System.out.print("B"); T else if (score >= 70.0) 2 System.out.print("C"); 0 else if (score >= 60.0) System.out.print("D"); 4 else System.out.print("F"); 50 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 25 7/29/2024 Object Oriented Programming(OOP) Trace if-else statement Suppose score is 70.0 Exit the if statement if (score >= 90.0) System.out.print("A"); I else if (score >= 80.0) System.out.print("B"); T else if (score >= 70.0) 2 System.out.print("C"); 0 else if (score >= 60.0) 4 System.out.print("D"); else System.out.print("F"); 51 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Note The else clause matches the most recent if clause in the same block. I T 2 0 4 52 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 52 26 7/29/2024 Object Oriented Programming(OOP) Note, cont. Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; I int j = 2; T int k = 3; 2 if (i > j) { 0 if (i > k) 4 System.out.println("A"); } else System.out.println("B"); 53 This statement prints B. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. 53 All rights reserved. Object Oriented Programming(OOP) Common Errors Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); Wrong { I area = radius*radius*PI; T System.out.println( 2 "The area for the circle of radius " + 0 radius + " is " + area); 4 } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. 54 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 27 7/29/2024 Object Oriented Programming(OOP) TIP if (number % 2 == 0 ) Equivalent even = true; boolean even else = number % 2 == 0 ; even = false; (a) (b) I T CAUTION 2 0 Equivalent if (even == true) if (even) 4 System.out.println( System.out.println( "It is even."); "It is even."); (a) (b) 55 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 55 Object Oriented Programming(OOP) Logical Operators Operator Name Description ! not logical negation && and logical conjunction I || or logical disjunction T ^ exclusive or logical exclusion 2 0 Truth Table for Operator ! 4 p !p Example (assume age = 24, weight = 140) true false !(age > 18) is false, because (age > 18) is true. false true !(weight == 150) is true, because (weight == 150) is false. 56 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 56 28 7/29/2024 Object Oriented Programming(OOP) Truth Table for Operator && p1 p2 p1 && p2 Example (assume age = 24, weight = 140) false false false (age 18) && (weight > 140) is false, because (weight > 140) is false I true true true (age > 18) && (weight >= 140) is true, because both (age > 18) and T (weight >= 140) are true. 2 Truth Table for Operator || 0 p1 p2 p1 || p2 Example (assume age = 24, weihgt = 140) 4 false false false false true true (age > 34) || (weight 34) is false, but (weight 14) || (weight >= 150) is false, because (age > 14) is true. 57 true true true Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Truth Table for Operator ^ p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140) false false false (age > 34) ^ (weight > 140) is true, because (age > 34) is false and (weight > 140) is false. false true true (age > 34) ^ (weight >= 140) is true, because (age > 34) is false but (weight >= 140) is true. I true false true (age > 14) ^ (weight > 140) is true, because (age > 14) is true and (weight T > 140) is false. 2 true true false 0 4 58 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 58 29 7/29/2024 Object Oriented Programming(OOP) Examples Here is a program that checks whether a number is divisible by 2 and 3, whether a number is divisible by 2 or 3, and whether a number is divisible by 2 or 3 but not both: I T 2 0 4 TestBooleanOperators Run 59 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Examples System.out.println("Is " + number + " divisible by 2 and 3? " + ((number % 2 == 0) && (number % 3 == 0))); I System.out.println("Is " + number + " divisible by 2 or 3? " + T TestBooleanOperators ((number % 2 == 0) || (number % 3 == 0))); 2 Run 0 4 System.out.println("Is " + number + " divisible by 2 or 3, but not both? " + ((number % 2 == 0) ^ (number % 3 == 0))); 60 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 60 30 7/29/2024 Object Oriented Programming(OOP) Examples TestBooleanOperators I T Run 2 0 4 61 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 61 Object Oriented Programming(OOP) switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; I break; T case 2: compute taxes for married file separately; 2 break; 0 case 3: compute taxes for head of household; 4 break; default: System.out.println("Errors: invalid status"); System.exit(1); } 62 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 62 31 7/29/2024 Object Oriented Programming(OOP) switch Statement Flow Chart I T 2 0 4 63 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 63 Object Oriented Programming(OOP) switch Statement Rules The switch-expression must yield a value of char, byte, switch (switch-expression) { short, or int type and must always be enclosed in case value1: statement(s)1; parentheses. break; I T The value1,..., and valueN must have case value2: statement(s)2; 2 the same data type as the value of the break; switch-expression. The resulting … 0 statements in the case statement are 4 case valueN: statement(s)N; executed when the value in the case statement matches the value of the break; switch-expression. Note that value1, default: statement(s)-for-default;..., and valueN are constant } expressions, meaning that they cannot contain variables in the expression, 64 such as 1 + x. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 64 32 7/29/2024 Object Oriented Programming(OOP) switch Statement Rules The keyword break is optional, but it switch (switch-expression) { should be used at the end of each case value1: statement(s)1; case in order to terminate the remainder of the switch statement. If break; the break statement is not present, case value2: statement(s)2; I the next case statement will be break; T executed. … 2 The default case, which is optional, case valueN: statement(s)N; 0 can be used to perform actions when break; 4 none of the specified cases matches the switch-expression. default: statement(s)-for-default; } When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a break statement or the end of the 65 switch Liang, statement Introduction is reached. to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. 65 All rights reserved. Object Oriented Programming(OOP) Trace switch statement Trace switch statement Suppose day is 2: Match case 2 switch (day) { switch (day) { I case 1: case 1: case 2: T case 2: case 3: case 3: 2 case 4: case 4: 0 case 5: System.out.println("Weekday"); case 5: System.out.println("Weekday"); 4 break; break; case 0: case 0: case 6: System.out.println("Weekend"); case 6: System.out.println("Weekend"); } } 66 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 33 7/29/2024 Object Oriented Programming(OOP) Trace switch statement Trace switch statement Fall through case 4 Fall through case 3 I switch (day) { switch (day) { case 1: T case 1: case 2: 2 case 2: case 3: 0 case 3: case 4: case 4: case 5: System.out.println("Weekday"); 4 case 5: System.out.println("Weekday"); break; break; case 0: case 0: case 6: System.out.println("Weekend"); case 6: System.out.println("Weekend"); } } 67 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Trace switch statement Trace switch statement Fall through case 5 Encounter break I switch (day) { switch (day) { T case 1: case 1: 2 case 2: case 2: 0 case 3: case 3: 4 case 4: case 4: case 5: System.out.println("Weekday"); case 5: System.out.println("Weekday"); break; break; case 0: case 0: case 6: System.out.println("Weekend"); case 6: System.out.println("Weekend"); } } 68 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 34 7/29/2024 Object Oriented Programming(OOP) Trace switch statement Exit the statement I switch (day) { T case 1: case 2: 2 case 3: 0 case 4: 4 case 5: System.out.println("Weekday"); break; case 0: case 6: System.out.println("Weekend"); } 69 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Conditional Operator, cont. boolean-expression ? exp1 : exp2 Conditional Operators if (x > 0) I y=1 T else 2 y = -1; 0 is equivalent to 4 y = (x > 0) ? 1 : -1; (boolean-expression) ? expression1 : expression2 Ternary operator Binary operator Unary operator 70 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 70 35 7/29/2024 Object Oriented Programming(OOP) Conditional Operator if (num % 2 == 0) System.out.println(num + “is even”); else I System.out.println(num + “is odd”); T 2 is equivalent to 0 4 System.out.println( (num % 2 == 0)? num + “is even” : num + “is odd”); 71 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Operator Precedence  var++, var--  +, - (Unary plus and minus), ++var,--var  (type) Casting I  ! (Not) T  *, /, % (Multiplication, division, and remainder) 2  +, - (Binary addition and subtraction) 0  = (Relational operators) 4  ==, !=; (Equality)  ^ (Exclusive OR)  && (Conditional AND) Short-circuit AND  || (Conditional OR) Short-circuit OR  =, +=, -=, *=, /=, %= (Assignment operator) 72 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 72 36 7/29/2024 Object Oriented Programming(OOP) Operator Precedence and Associativity The expression in the parentheses is evaluated first. (Parentheses can be nested, in which case the expression in the inner parentheses is executed first.) When evaluating an I expression without parentheses, the operators are applied T 2 according to the precedence rule and the associativity rule. 0 4 If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left-associative. 73 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Operator Associativity When two operators with the same precedence are evaluated, the associativity of the operators I determines the order of evaluation. All binary T operators except assignment operators are left- 2 associative. 0 4 a – b + c – d is equivalent to ((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5)) 74 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 74 37 7/29/2024 Object Oriented Programming(OOP) Example Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows: I 3 + 4 * 4 > 5 * (4 + 3) - 1 (1 ) in sid e p a re n th e se s firs t T 3 + 4 * 4 > 5 * 7 – 1 2 (2 ) m u ltip lic a tio n 3 + 16 > 5 * 7 – 1 0 (3 ) m u ltip lic a tio n 4 3 + 16 > 35 – 1 (4 ) a d d itio n 19 > 35 – 1 (5 ) su b tra c tio n 19 > 34 (6 ) g re a te r th a n false 75 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 75 Object Oriented Programming(OOP) Mathematical Functions, Characters, I T and Strings 2 0 4 76 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 76 38 7/29/2024 Loops Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Opening Problem Problem: System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); I 100 … T times … 2 … System.out.println("Welcome to Java!"); 0 System.out.println("Welcome to Java!"); 4 System.out.println("Welcome to Java!"); Introducing while Loops int count = 0; while (count < 100) { System.out.println("Welcome to Java"); 78 count++; Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. } All rights reserved. 39 7/29/2024 Objectives  To write programs for executing statements repeatedly using a while loop.  To follow the loop design strategy to develop loops.  To control a loop with a sentinel value.  To obtain large input from a file using input redirection rather than typing from the keyboard  To write loops using do-while statements.  To write loops using for statements.  To discover the similarities and differences of three types of loop statements.  To write nested loops.  To learn the techniques for minimizing numerical errors.  To learn loops from a variety of examples (GCD, FutureTuition, Dec2Hex.  To implement program control with break and continue. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.79 Object Oriented Programming(OOP) while Loop Flow Chart int count = 0; while (loop-continuation-condition) { while (count < 100) { // loop-body; System.out.println("Welcome to Java!"); Statement(s); count++; I } } T 2 0 4 80 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 80 40 7/29/2024 Object Oriented Programming(OOP) Trace while Loop Initialize count int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; I } T Trace while Loop, cont. 2 (count < 2) is true 0 int count = 0; 4 while (count < 2) { System.out.println("Welcome to Java!"); count++; } 81 81 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Object Oriented Programming(OOP) Trace while Loop, cont. Print Welcome to Java int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } I T Trace while Loop, cont. 2 Increase count by 1 0 int count = 0; count is 1 now 4 while (count < 2) { System.out.println("Welcome to Java!"); count++; } 82 82 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 41 7/29/2024 Object Oriented Programming(OOP) Trace while Loop, cont. (count < 2) is still true since count is 1 int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; I } T Trace while Loop, cont. 2 0 Print Welcome to Java int count = 0; 4 while (count < 2) { System.out.println("Welcome to Java!"); count++; } 83 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 83 animation Object Oriented Programming(OOP) Trace while Loop, cont. int count = 0; Increase count by 1 count is 2 now while (count < 2) { System.out.println("Welcome to Java!"); count++; } I T Trace while Loop, cont. 2 (count < 2) is false since count is 2 now int count = 0; 0 while (count < 2) { 4 System.out.println("Welcome to Java!"); count++; } 84 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 84 42 7/29/2024 Object Oriented Programming(OOP) Trace while Loop The loop exits. Execute the next int count = 0; statement after the loop. while (count < 2) { System.out.println("Welcome to Java!"); count++; I } T 2 0 4 85 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 85 Object Oriented Programming(OOP) Problem: Repeat Addition Until Correct Recall that Listing 3.1 AdditionQuiz.java gives a program that prompts the user to enter an answer for a question on addition of two single digits. Using a loop, you can now rewrite the program to let the user enter a new I answer until it is correct. T 2 0 IMPORTANT NOTE: If you cannot run the buttons, see https://liveexample.pearsoncmg.com/slide/javaslidenote.doc. 4 RepeatAdditionQuiz Run 86 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 43 7/29/2024 Object Oriented Programming(OOP) Problem: Guessing Numbers Write a program that randomly generates an integer between 0 and 100, inclusive. The program prompts the user to enter a number continuously until the number matches the randomly generated number. For each user input, the program tells the user whether the input is too low or too high, so the user can choose the next input intelligently. Here is a sample run: I T 2 GuessNumberOneTim Run 0 e GuessNumber Run 4 87 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 87 Object Oriented Programming(OOP) Problem: An Advanced Math Learning Tool The Math subtraction learning tool program generates just one question for each run. You can use a loop to generate questions repeatedly. This example gives a program that generates five questions and reports the number of the correct answers after a student answers all five questions. I T SubtractionQuizLoop Run 2 0 4 88 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 88 44 7/29/2024 Object Oriented Programming(OOP) Problem: An Advanced Math Learning Tool The Math subtraction learning tool program generates just one question for each run. You can use a loop to generate questions repeatedly. This example gives a program that generates five questions and reports the number of the correct answers after a student answers all five questions. I T SubtractionQuizLoop Run 2 0 4 89 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 89 Object Oriented Programming(OOP) Ending a Loop with a Sentinel Value Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value. Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. I T 2 0 SentinelValue Run 4 90 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 90 45 7/29/2024 Object Oriented Programming(OOP) Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations for some values, using them could result in imprecise counter values and inaccurate results. Consider the following code for computing 1 + 0.9 + 0.8 +... + 0.1: I double item = 1; double sum = 0; T while (item != 0) 2 { // No guarantee item will be 0 0 sum += item; 4 item -= 0.1; } System.out.println(sum); 91 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 91 Object Oriented Programming(OOP) do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition); I T 2 0 4 92 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 92 46 7/29/2024 Object Oriented Programming(OOP) for Loops for (initial-action; loop-continuation- int i; condition; action-after-each-iteration) { for (i = 0; i < 100; i++) { // loop body; System.out.println( Statement(s); "Welcome to Java!"); I } } T 2 0 4 93 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 93 Object Oriented Programming(OOP) Trace fo

Use Quizgecko on...
Browser
Browser