Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Similar presentations


Presentation on theme: "Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3."— Presentation transcript:

1 Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3

2 Overview of Previous Lecture To write Java programs to perform simple calculations (§2.2). To obtain input from the console using the Scanner class (§2.3). To use identifiers to name variables, constants, methods, and classes (§2.4). To use variables to store data (§§2.5-2.6). To program with assignment statements and assignment expressions (§2.6). To use constants to store permanent data (§2.7). To declare Java primitive data types: byte, short, int, long, float, double, and char (§§2.8.1). To use Java operators to write numeric expressions (§§2.8.2–2.8.3). To display current time (§2.9). 10/9/20152 COSC-1336, Lecture 3

3 Overview of Previous Lecture (cont) To use short hand operators (§2.10). To cast value of one type to another type (§2.11). To compute loan payment (§2.12). To represent characters using the char type (§2.13). To compute monetary changes (§2.14). To represent a string using the String type (§2.15). To become familiar with Java documentation, programming style, and naming conventions (§2.16). To distinguish syntax errors, runtime errors, and logic errors and debug errors (§2.17). (GUI) To obtain input using the JOptionPane input dialog boxes (§2.18). 10/9/20153 COSC-1336, Lecture 3

4 Motivation of the current lecture In the preceding chapter, you learned how to solve practical problems programmatically, namely Java primitive data types and related subjects, such as variables, constants, data types, operators, expressions, and input and output. Considering the Java program that obtains hours and minutes from seconds (calculating time and display it), the number of seconds read from the input has to be positive – hence selected. 10/9/20154 COSC-1336, Lecture 3

5 Overview of This Lecture  To declare boolean type and write Boolean expressions using comparison operators (§3.2).  To program AdditionQuiz using Boolean expressions (§3.3).  To implement selection control using one-way if statements (§3.4)  To program the GuessBirthday game using one-way if statements (§3.5).  To implement selection control using two-way if statements (§3.6).  To implement selection control using nested if statements (§3.7).  To avoid common errors in if statements (§3.8).  To program using selection statements for a variety of examples ( BMI, ComputeTax, SubtractionQuiz ) (§3.9-3.11). 10/9/20155 COSC-1336, Lecture 3

6 Overview of This Lecture (cont.)  To combine conditions using logical operators ( &&, ||, and ! ) (§3.12).  To program using selection statements with combined conditions ( LeapYear, Lottery) (§§3.13-3.14).  To implement selection control using switch statements (§3.15). F To write expressions using the conditional operator (§3.16).  To format output using the System.out.printf() method and to format strings using the String.format() method (§3.17). F To examine the rules governing operator precedence and associativity (§3.18). F (GUI) To get user confirmation using confirmation dialogs (§3.19). 10/9/20156 COSC-1336, Lecture 3

7 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. boolean b = (1 > 2); 10/9/20157 COSC-1336, Lecture 3

8 Comparison Operators Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to 10/9/20158 COSC-1336, Lecture 3

9 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 + 9? ” to the student.  After the student types the answer, the program displays a message to indicate whether the answer is true or false. 10/9/20159 COSC-1336, Lecture 3

10 AdditionQuiz.java import java.util.Scanner; public class AdditionQuiz { public static void main(String[] args) { int number1 = (int)(System.currentTimeMillis() % 10); int number2 = (int)(System.currentTimeMillis() / 7 % 10); Scanner input = new Scanner(System.in); System.out.print("What is " + number1 + " + " + number2 + "? "); int answer = input.nextInt(); System.out.println(number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer)); } 10/9/201510 COSC-1336, Lecture 3

11 Compiling and running AdditionQuiz.java 10/9/201511 COSC-1336, Lecture 3

12 One-way if Statements if (boolean-expression) { statement(s); } if (radius >= 0) { area = radius * radius * PI; System.out.println("The area for the " + " circle of radius " + radius + " is " + area); } 10/9/201512 COSC-1336, Lecture 3

13 Note  It’s like: “buildings with one level don’t need elevators”.  Similarly, the if statements with just one statement don’t need to embed that single statement into a block of statements (surrounded by { and } ). 10/9/201513 COSC-1336, Lecture 3

14 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. 10/9/201514 COSC-1336, Lecture 3

15 SimpleIfDemo.java import java.util.Scanner; public class SimpleIfDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter an integer: "); int number = input.nextInt(); if (number % 5 == 0) System.out.println("HiFive"); if (number % 2 == 0) System.out.println("HiEven"); } 10/9/201515 COSC-1336, Lecture 3

16 Compiling and running SimpleIfDemo.java 10/9/201516 COSC-1336, Lecture 3

17 The Two-way if Statement if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } 10/9/201517 COSC-1336, Lecture 3

18 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"); } 10/9/201518 COSC-1336, Lecture 3

19 Multiple Alternative if Statements 10/9/201519 COSC-1336, Lecture 3

20 Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0The condition is false 10/9/201520 COSC-1336, Lecture 3

21 Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0The condition is false 10/9/201521 COSC-1336, Lecture 3

22 Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0The condition is true 10/9/201522 COSC-1336, Lecture 3

23 Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0 grade is C 10/9/201523 COSC-1336, Lecture 3

24 Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0Exit the if statement 10/9/201524 COSC-1336, Lecture 3

25 Note The else clause matches the most recent if clause in the same block. 10/9/201525 COSC-1336, Lecture 3

26 Note (cont.) Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); This statement prints B. 10/9/201526 COSC-1336, Lecture 3

27 Common Errors 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); } 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. Wrong 10/9/201527 COSC-1336, Lecture 3

28 TIP 10/9/201528 COSC-1336, Lecture 3

29 CAUTION 10/9/201529 COSC-1336, Lecture 3

30 Problem: Body Mass Index Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older is as follows: 10/9/201530 COSC-1336, Lecture 3

31 ComputeBMI.java import java.util.Scanner; public class ComputeBMI { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter weight in pounds System.out.print("Enter weight in pounds: "); double weight = input.nextDouble(); // Prompt the user to enter height in inches System.out.print("Enter height in inches: "); double height = input.nextDouble(); 10/9/201531 COSC-1336, Lecture 3

32 ComputeBMI.java (cont.) final double KILOGRAMS_PER_POUND = 0.45359237; // Constant final double METERS_PER_INCH = 0.0254; // Constant // Compute BMI double weightInKilogram = weight * KILOGRAMS_PER_POUND; double heightInMeters = height * METERS_PER_INCH; double bmi = weightInKilogram / (heightInMeters * heightInMeters); // Display result System.out.printf("Your BMI is %5.2f\n", bmi); 10/9/201532 COSC-1336, Lecture 3

33 ComputeBMI.java (cont.) if (bmi < 16) System.out.println("You are seriously underweight"); else if (bmi < 18) System.out.println("You are underweight"); else if (bmi < 24) System.out.println("You are normal weight"); else if (bmi < 29) System.out.println("You are overweight"); else if (bmi < 35) System.out.println("You are seriously overweight"); else System.out.println("You are gravely overweight"); } 10/9/201533 COSC-1336, Lecture 3

34 Running ComputeBMI.java 10/9/201534 COSC-1336, Lecture 3

35 Problem: An Improved Math Learning Tool This example creates a program to teach a first grade child how to learn subtractions. The program randomly generates two single-digit integers number1 and number2 with number1 > number2 and displays a question such as “ What is 9 – 2? ” to the student. After the student types the answer in the input dialog box, the program indicates if the answer is correct. The method Math.random() generates a double number from interval [0,1). 10/9/201535 COSC-1336, Lecture 3

36 SubtractionQuiz.java import java.util.Scanner; public class SubtractionQuiz { public static void main(String[] args) { // 1.Generate two random single-digit integers int number1 = (int)(Math.random() * 10); int number2 = (int)(Math.random() * 10); // 2.If number1 < number2, swap number1 with number2 if (number1 < number2) { int temp = number1; number1 = number2; number2 = temp; } 10/9/201536 COSC-1336, Lecture 3

37 SubtractionQuiz.java (cont.) // 3.Prompt the answer “what is number1 – number2?” System.out.print("What is " + number1 + " - " + number2 + "? "); Scanner input = new Scanner(System.in); int answer = input.nextInt(); // 4.Grade the answer and display the result if (number1 - number2 == answer) System.out.println("You are correct!"); else System.out.println("Your answer is wrong.\n" + number1 + " - " + number2 + " should be " + (number1 - number2)); } 10/9/201537 COSC-1336, Lecture 3

38 Compiling and running SubtractionQuiz.java 10/9/201538 COSC-1336, Lecture 3

39 Logical Operators Operator Name ! not && and || or ^ exclusive or 10/9/201539 COSC-1336, Lecture 3

40 Truth Table for Operator ! 10/9/201540 COSC-1336, Lecture 3

41 Truth Table for Operator && 10/9/201541 COSC-1336, Lecture 3

42 Truth Table for Operator || 10/9/201542 COSC-1336, Lecture 3

43 Truth Table for Operator ^ 10/9/201543 COSC-1336, Lecture 3 Given A and B two Boolean variables, A ^ B means “exclusive or”. That is, very similar with the || operator, except their values cannot be equal. Hence A ^ B is true if and only if A and B have different values.

44 Summary of truth tables for Java Boolean operators A B A || B A && B A ^ B !A false false false false false true true false true false true false false true true false true true true true true true false false 10/9/2015 COSC-1336, Lecture 3 44

45 Example  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. 10/9/201545 COSC-1336, Lecture 3

46 TestBooleanOperators.java import java.util.Scanner; public class TestBooleanOperators { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int number = input.nextInt(); System.out.println("Is " + number + " divisible by 2 and 3? " + ((number % 2 == 0) && (number % 3 == 0))); System.out.println("Is " + number + " divisible by 2 or 3? " + ((number % 2 == 0) || (number % 3 == 0))); System.out.println("Is " + number + " divisible by 2 or 3, but not both? " + ((number % 2 == 0) ^ (number % 3 == 0))); } 10/9/201546 COSC-1336, Lecture 3

47 Compiling and running TestBooleanOperators.java 10/9/201547 COSC-1336, Lecture 3

48 The bitwise AND " & " operator Returns 1 if any of the two bits is 1 and it returns 0 if any of the bits is 0. 5 has the binary representation:  00000101 6 has the binary representation:  00000110 5 & 6 has the binary representation:  00000100,  which means 4. 10/9/201548 COSC-1336, Lecture 3

49 Example of using the ‘ & ’ operator int x = 3 & 3; int y = 4 & 6; int z = 5 & 6; How much are x, y, and z ? Hint: use the binary representations of 3, 4, 5, 6. x = 3, y = 4, z = 4. 10/9/201549 COSC-1336, Lecture 3

50 The bitwise OR “ | " operator Returns 0 if both of the two bits are 0 and it returns 1 if any of the bits is 1. 5 has the binary representation:  00000101 6 has the binary representation:  00000110 5 | 6 has the binary representation:  00000111,  which means 7. 10/9/201550 COSC-1336, Lecture 3

51 Example of using the ‘ | ’ operator int x = 3 | 3; int y = 4 | 6; int z = 5 | 6; How much are x, y, and z ? Hint: use the binary representations of 3, 4, 5, 6. x = 3, y = 6, z = 7. 10/9/201551 COSC-1336, Lecture 3

52 switch Statement Rules switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for- default; } The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1,..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1,..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x. 10/9/201552 COSC-1336, Lecture 3

53 switch Statement Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for- default; } The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end. 10/9/201553 COSC-1336, Lecture 3

54 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Suppose ch is 'a': animation 10/9/201554 COSC-1336, Lecture 3

55 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } ch is 'a': animation 10/9/201555 COSC-1336, Lecture 3

56 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation 10/9/201556 COSC-1336, Lecture 3

57 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation 10/9/201557 COSC-1336, Lecture 3

58 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Execute this line animation 10/9/201558 COSC-1336, Lecture 3

59 Trace switch statement switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch); } Next statement; Execute next statement animation 10/9/201559 COSC-1336, Lecture 3

60 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Suppose ch is 'a': animation 10/9/201560 COSC-1336, Lecture 3

61 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } ch is 'a': animation 10/9/201561 COSC-1336, Lecture 3

62 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Execute this line animation 10/9/201562 COSC-1336, Lecture 3

63 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Execute this line animation 10/9/201563 COSC-1336, Lecture 3

64 Trace switch statement switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break ; case 'c': System.out.println(ch); } Next statement; Execute next statement animation 10/9/201564 COSC-1336, Lecture 3

65 The Conditional (ternary) Operator if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; Syntax: (boolean-expression) ? expression1 : expression2 Semantics: if boolean-expression evaluates to true, then the value of expression1 is returned, otherwise the value of expression2. 10/9/201565 COSC-1336, Lecture 3

66 The 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" ); 10/9/201566 COSC-1336, Lecture 3

67 Formatting Output  Use the printf() method call: System.out.printf(format, items);  where format is a String that may consist of substrings and format specifiers.  A format specifier specifies how an item should be displayed.  An item may be a numeric value, character, boolean value, or a String.  Each specifier begins with a percent sign. 10/9/201567 COSC-1336, Lecture 3

68 Frequently-Used Specifiers Specifier OutputExample %b a boolean value true or false %c a character 'a' %d a decimal integer 200 %f a floating-point number 45.460000 %e a number in standard scientific notation 4.556000e+01 %s a string "Java is cool" 10/9/201568 COSC-1336, Lecture 3

69 Operator Precedence var++, var-- +, - (Unary plus and minus), ++var, --var (type) Casting ! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction), >= (Comparison) ==, !=; (Equality) ^ (Exclusive OR) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator) 10/9/201569 COSC-1336, Lecture 3

70 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 expression without parentheses, the operators are applied according to the precedence rule and the associativity rule. 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. 10/9/201570 COSC-1336, Lecture 3

71 Operator Associativity When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left- associative. 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)) 10/9/201571 COSC-1336, Lecture 3

72 Example Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows: 10/9/201572 COSC-1336, Lecture 3

73 Summary  To declare boolean type and write Boolean expressions using comparison operators (§3.2).  To program AdditionQuiz using Boolean expressions (§3.3).  To implement selection control using one-way if statements (§3.4)  To program the GuessBirthday game using one-way if statements (§3.5).  To implement selection control using two-way if statements (§3.6).  To implement selection control using nested if statements (§3.7).  To avoid common errors in if statements (§3.8).  To program using selection statements for a variety of examples ( BMI, ComputeTax, SubtractionQuiz ) (§3.9-3.11). 10/9/201573 COSC-1336, Lecture 3

74 Summary (cont.)  To combine conditions using logical operators ( &&, ||, and ! ) (§3.12).  To program using selection statements with combined conditions ( LeapYear, Lottery) (§§3.13-3.14).  To implement selection control using switch statements (§3.15). F To write expressions using the conditional operator (§3.16).  To format output using the System.out.printf() method and to format strings using the String.format() method (§3.17). F To examine the rules governing operator precedence and associativity (§3.18). F (GUI) To get user confirmation using confirmation dialogs (§3.19). 10/9/201574 COSC-1336, Lecture 3

75 Reading suggestions From [Liang: Introduction to Java programming: Eight Edition, 2011 Pearson Education, 0132130807]  Chapter 3 (Selections) 10/9/201575 COSC-1336, Lecture 3

76 Coming up next From [Liang: Introduction to Java programming: Eight Edition, 2011 Pearson Education, 0132130807]  Chapter 4 ( Loops ) 10/9/201576 COSC-1336, Lecture 3

77 Thank you for your attention! Questions? 10/9/201577 COSC-1336, Lecture 3


Download ppt "Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3."

Similar presentations


Ads by Google