Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.

Similar presentations


Presentation on theme: "1 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections."— Presentation transcript:

1 1 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections

2 2 2 Motivations If you assigned a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.java, the program would print an invalid result. If the radius is negative, you don't want the program to compute the area. How can you deal with this situation? if (radius < 0) { System.out.println("Incorrect input"); } else { area = radius * radius * 3.14159; System.out.println("Area is " + area); } if (radius < 0) { System.out.println("Incorrect input"); } else { area = radius * radius * 3.14159; System.out.println("Area is " + area); }

3 3 3 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);

4 4 4 Relational Operators double radius = 1; System.out.println(radius > 0);

5 5 5 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.

6 6

7 7 7 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); }

8 8 8 Note

9 9 Example

10 10 The Two-way if Statement if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; }

11 11 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"); }

12 12 Multiple Alternative if Statements

13 13 Multi-Way if-else Statements

14 14 Caution: Dangling else Ambiguity The else clause matches the most recent if clause in the same block.

15 15 Caution: (Continue…) 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.

16 16 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. Logic Error

17 17 CAUTION if (even == true) System.out.println("It is even."); if (even) System.out.println ( "It is even.");

18 18 TIP: Simplifying Boolean Variable Assignment if (number % 2 == 0) even = true; else even = false; boolean even = number % 2 == 0;

19 19 Problem: Computing Taxes The US federal personal income tax is calculated based on the filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2009 are shown below.

20 20 Problem: Computing Taxes, cont. if (status == 0) { // Compute tax for single filers } else if (status == 1) { // Compute tax for married file jointly // or qualifying widow(er) } else if (status == 2) { // Compute tax for married file separately } else if (status == 3) { // Compute tax for head of household } else { // Display wrong status }

21 21

22 22

23 23 Logical Operators

24 24 Truth Table for Operator !

25 25 Truth Table for Operator &&

26 26 Truth Table for Operator ||

27 27 Truth Table for Operator ^

28 28 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:

29 29 The & and | Operators If x is 1, what is x after this expression? (x > 1) & (x++ < 10) If x is 1, what is x after this expression? (1 > x) && ( 1 > x++) How about (1 == x) | (10 > x++)? (1 == x) || (10 > x++)?

30 30 Problem: Determining Leap Year? This program first prompts the user to enter a year as an int value and checks if it is a leap year. A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400. (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)

31 31

32 32 switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); System.exit(1); }

33 33 switch Statement Flow Chart

34 34 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.

35 35 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. 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 switch statement is reached.

36 36 Conditional Expressions General syntax: (boolean-expression) ? expression1 : expression2 if (x > 0) y = 1 else y = -1; y = (x > 0) ? 1 : -1; is equivalent to max = (num1 > num2) ? num1 : num2;

37 37 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”);

38 38 Operator Precedence

39 39 Example Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows:

40 40 Character Data Type char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode) Four hexadecimal digits. NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b. char ch = 'a'; System.out.println(++ch);

41 41 Unicode Format Java characters use Unicode, a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent 65536 characters. Unicode \u03b1 \u03b2 \u03b3 for three Greek letters

42 42 ASCII Code for Commonly Used Characters

43 43 Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

44 44 ASCII Character Set, cont. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

45 45 Escape Sequences for Special Characters System.out.println("He said "Java is fun""); System.out.println("He said \"Java is fun\""); He said "Java is fun"

46 46 Escape Sequences for Special Characters

47 47 Casting between char and Numeric Types int i = ' a ' ; // Same as int i = (int) ' a ' ; char c = 97; // Same as char c = (char)97;

48 48 Comparing and Testing Characters if (ch >= 'A' && ch <= 'Z') System.out.println(ch + " is an uppercase letter"); else if (ch >= 'a' && ch <= 'z') System.out.println(ch + " is a lowercase letter"); else if (ch >= '0' && ch <= '9') System.out.println(ch + " is a numeric character");

49 49 Methods in the Character Class

50 50 The String Type The char type only represents one character. To represent a string of characters, use the data type called String. Here, message is a reference variable that references a string object with contents Welcome to Java. String is actually a predefined class in the Java library The String type is not a primitive type. It is known as a reference type. String message = "Welcome to Java";

51 51 Simple Methods for String Objects

52 52 Getting String Length String message = "Welcome to Java"; System.out.println("The length of " + message + " is “ + message.length()); int x = message.length(); If (x<= 10) System.out.println( message ); else System.out.println( “too long to print” );

53 53 Getting Characters from a String String message = "Welcome to Java"; System.out.println("The first character in message is “ + message.charAt(0));

54 54 Converting Strings string st1= "Welcome“; System.out.println(st1 + “ “ + st1.toLowerCase()); string st2= st1.toLowerCase(); st2 = st1.toUpperCase(); " Welcome ".trim() returns a new string, Welcome.

55 55 String Concatenation String s3 = s1.concat(s2); or String s3 = s1 + s2; // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

56 56 Reading a String from the Console Scanner input = new Scanner(System.in); System.out.print("Enter three words separated by spaces: "); String s1 = input.next(); String s2 = input.next(); String s3 = input.next(); System.out.println("s1 is " + s1); System.out.println("s2 is " + s2); System.out.println("s3 is " + s3);

57 57 Reading a Character from the Console Scanner input = new Scanner(System.in); System.out.print("Enter a character: "); String s = input.nextLine(); char ch = s.charAt(0); System.out.println("The character entered is " + ch);

58 58 Comparing Strings

59 59 Obtaining Substrings

60 60 Finding a Character or a Substring in a String

61 61 Finding a Character or a Substring in a String int k = s.indexOf(' '); String firstName = s.substring(0, k); String lastName = s.substring(k + 1);

62 62 Conversion between Strings and Numbers int intValue = Integer.parseInt(intString); double doubleValue = Double.parseDouble(doubleString); String s = number + "";

63 63 Problem: Guessing Birthday GuessBirthday The program can guess your birth date. Run to see how it works.

64 64 Mathematics Basis for the Game 19 is 10011 in binary. 7 is 111 in binary. 23 is 11101 in binary

65 65 Case Study: Converting a Hexadecimal Digit to a Decimal Value Write a program that converts a hexadecimal digit into a decimal value. HexDigit2DecRun

66 66 Formatting Output Use the printf statement. 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.

67 67 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"

68 68 FormatDemo The example gives a program that uses printf to display a table. FormatDemoRun


Download ppt "1 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections."

Similar presentations


Ads by Google