1 / 77

Stefan Andrei

Learn Java basics including simple calculations, input/output, variables, constants, data types, operators, and expressions. Explore Boolean expressions, selection control, if statements, switch statements, and more with practical examples.

akaren
Download Presentation

Stefan Andrei

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming Fundamentals I (COSC-1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 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). 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). 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. 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 ifstatements (§3.8). • To program using selection statements for a variety of examples (BMI, ComputeTax, SubtractionQuiz) (§3.9-3.11). 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 switchstatements (§3.15). • 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). • To examine the rules governing operator precedence and associativity (§3.18). • (GUI) To get user confirmation using confirmation dialogs (§3.19). 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); 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 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. COSC-1336, Lecture 3

  10. AdditionQuiz.java importjava.util.Scanner; publicclassAdditionQuiz { publicstaticvoid 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)); } } COSC-1336, Lecture 3

  11. Compiling and running AdditionQuiz.java COSC-1336, Lecture 3

  12. One-way if Statements if (radius >= 0) { area = radius * radius * PI; System.out.println("The area for the " + " circle of radius " + radius + " is " + area); } if (boolean-expression) { statement(s); } 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 }). 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. COSC-1336, Lecture 3

  15. SimpleIfDemo.java import java.util.Scanner; publicclass SimpleIfDemo { publicstaticvoid 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"); } } COSC-1336, Lecture 3

  16. Compiling and running SimpleIfDemo.java 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; } COSC-1336, Lecture 3

  18. if...elseExample 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"); } COSC-1336, Lecture 3

  19. Multiple Alternative if Statements COSC-1336, Lecture 3

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

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

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

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

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

  25. Note • The else clause matches the most recent if clause in the same block. 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. 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 COSC-1336, Lecture 3

  28. TIP COSC-1336, Lecture 3

  29. CAUTION 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: COSC-1336, Lecture 3

  31. ComputeBMI.java import java.util.Scanner; publicclass ComputeBMI { publicstaticvoid 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(); COSC-1336, Lecture 3

  32. ComputeBMI.java (cont.) finaldouble KILOGRAMS_PER_POUND = 0.45359237; // Constant finaldouble 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); COSC-1336, Lecture 3

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

  34. Running ComputeBMI.java 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 adouble number from interval [0,1). COSC-1336, Lecture 3

  36. SubtractionQuiz.java import java.util.Scanner; publicclass SubtractionQuiz { publicstaticvoid 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; } 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)); } } COSC-1336, Lecture 3

  38. Compiling and running SubtractionQuiz.java COSC-1336, Lecture 3

  39. Logical Operators Operator Name ! not && and || or ^ exclusive or COSC-1336, Lecture 3

  40. Truth Table for Operator ! COSC-1336, Lecture 3

  41. Truth Table for Operator && COSC-1336, Lecture 3

  42. Truth Table for Operator || COSC-1336, Lecture 3

  43. Truth Table for Operator^ • 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. COSC-1336, Lecture 3

  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 COSC-1336, Lecture 3

  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. 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))); } } COSC-1336, Lecture 3

  47. Compiling and running TestBooleanOperators.java 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. 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. 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. COSC-1336, Lecture 3

More Related