Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 4 Selection Control Statements The if Statement More About Selection Errors.

Similar presentations


Presentation on theme: "Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 4 Selection Control Statements The if Statement More About Selection Errors."— Presentation transcript:

1 Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 4 Selection Control Statements The if Statement More About Selection Errors Testing and Debugging Artificial Intelligence

2 Programming and Problem Solving With Java 2 The if Statement  Making a decision

3 Programming and Problem Solving With Java 3 The if Statement

4 Programming and Problem Solving With Java 4 The if Statement

5 Programming and Problem Solving With Java 5 Relational Operators with if  Relational operator: compares two values  Relational operators in Java  Notice!! Test for equality is ==

6 Programming and Problem Solving With Java 6 Turtle Graphics Constants  Makes if statements more readable if (Turtle.MAX_ROW - myTurtle.atRow() < 10) { myTurtle.turnRight(180); }

7 Programming and Problem Solving With Java 7 Methods that Provide Turtle Info

8 Programming and Problem Solving With Java 8 Relational Operands: Primitives  Compare two primitive values  Value of type byte, int, short, long, float, …  Relational operator tells how the values compare  Example if (3 < 5) …  3 and 5 are integers  3 is less than 5, so condition is true

9 Programming and Problem Solving With Java 9 Relational Operands: Objects  Compare two objects  Object of class String, Turtle, …  Relational operator compares objects, not their values  Example String message1 = "Hi there"; String message2 = "Hi " + "there"; if (message1 == message2) { System.out.println("The messages are the same"); } if (message1 != message2) { System.out.println("The messages are different"); }  message1 and message2 refer to different objects false true displays message1 message2 Hi there

10 Programming and Problem Solving With Java 10 String Methods: compareTo()  a.compareTo(b) returns  0 if a == b  < 0 if a < b  > 0 if a > b  Example String a = " Hi there"; String b = " HI THERE"; if (a.compareTo(b) == 0) { System.out.println("Yes"); }  No output: a and b have different values

11 Programming and Problem Solving With Java 11 String Methods: endsWith()  a.endsWith(b) returns  true if the last characters in a are b  false otherwise  Example String a = " Hi there"; if(a.endsWith("ere")) { System.out.println("Yes"); }  Displays Yes: the last three characters of a are "ere"

12 Programming and Problem Solving With Java 12 Strings: equals()  a.equals(b) returns  true if the values of a and b are the same  false otherwise  Example String a = " Hi there"; String b = " HI THERE"; if(a.equals(b)) { System.out.println("Yes"); }  Displays nothing: a and b have the different values (upper and lower case letters are different characters)

13 Programming and Problem Solving With Java 13 Strings: equalsIgnoreCase()  a.equalsIgnoreCase(b) returns  true if the values of a and b are the same, regardless of upper and lower case differences  false otherwise  Example String a = " Hi there"; String b = " HI THERE"; if(a.equalsIgnoreCase(b)) { System.out.println("Yes"); }  Displays Yes: a and b have the same values (ignoring case)

14 Programming and Problem Solving With Java 14 String Methods: startsWith()  a.startsWith(b) returns  true if the first characters in a are b  false otherwise  Example String a = " Hi there"; if(a.startsWith(" Hi")) { System.out.println("Yes"); }  Displays Yes: the first four characters of a are " Hi" (two spaces at beginning)

15 Programming and Problem Solving With Java 15 The char Type  Used for storing single characters  Literal values surrounded by single quotes 'A' 'a' '?' '9' '!'  Displaying a character System.out.println('B');  Upper and lower case characters are different  'a' != 'A'

16 Programming and Problem Solving With Java 16 The if Statement: char char choice; int firstNum, secondNum; // Ask user for first number firstNum = Keyboard.readInt("Enter first integer: "); // Ask user for second number secondNum = Keyboard.readInt("Enter second integer: "); // Ask user which operation to use choice = Keyboard.readChar("Enter A to add the numbers, " + "M to multiply them: "); // Display the results if (choice == 'A') { System.out.println("The sum is " + (firstNum + secondNum)); } if (choice == 'M') { System.out.println("The product is " + (firstNum * secondNum)); } Enter first integer: 23 Enter second integer: 42 Enter A to add the numbers, M to multiply them: A The sum is 65

17 Programming and Problem Solving With Java 17 The readChar() Method  Three ways to use readChar()  No prompt message choice = Keyboard.readChar();  Prompting message choice = Keyboard.readChar("Enter A to add the numbers, " + "M to multiply them: ");  Prompting message and restricted input choice = Keyboard.readChar("Enter A to add the numbers, " + "M to multiply them: ", "AM"); Enter A to add the numbers, M to multiply them: X Please enter one of these characters: AM Enter A to add the numbers, M to multiply them: G Please enter one of these characters: AM Enter A to add the numbers, M to multiply them: A

18 Programming and Problem Solving With Java 18 Comparing Characters  Computer compares Unicode values of characters if ('A' < 'B')...  Unicode value of 'A' is 65  Unicode value of 'B' is 66  'A' < 'B' becomes 65 < 66

19 Programming and Problem Solving With Java 19 Compound Statements  Compound statement : one or more statements surrounded by braces { x++; System.out.print("Hello"); }  Compiler treats as a single statement  if statement operates on a single statement if (condition)if (myTurtle.direction() > 180) statement myTurtle.move(100); No braces!

20 Programming and Problem Solving With Java 20 if with Compound Statements  Must use compound statement if more than one if (condition)if (myTurtle.direction() > 180){ statement 1 myTurtle.move(100); statement 2 myTurtle.turnRight(90);}  Good programming practice: always use compound statement with if  Shows structure more clearly  Can easily add statements to if-body  Avoid dangling-else problem (coming up shortly)

21 Programming and Problem Solving With Java 21 The else Clause  else clause an optional part of if statement  Computer executes one of 2 statements if (condition) { statements } else { statements }  If condition is true, execute if-body  Otherwise, else-body

22 Programming and Problem Solving With Java 22 The else Clause

23 Programming and Problem Solving With Java 23 The else Clause: turn() Method  turn() method for turtle that turns 0 - 360 o  Approach  If the angle is 180 or less, do single turnRight().  Otherwise, do turnRight(180), then turnRight the rest // turn: Turn to the right, from 0 to 360 degrees public void turn(int degrees) throws TurtleException { if (degrees <= 180) { this.turnRight(degrees); } else { this.turnRight(180); this.turnRight(degrees - 180); }

24 Programming and Problem Solving With Java 24 Nested if Statements  Nested decision: One decision depends on the result of another

25 Programming and Problem Solving With Java 25 Nested if Statements  Example: Cost of first-class letter  40 cents for first ounce, 30 cents for each additional  Must be between 1 and 11 ounces  After reading weight if (weight > 0) // Outer-if statement { if (weight <= FIRST_CLASS_LIMIT) // Inner-if statement { costInCents = FIRST_OUNCE_COST + ADDITIONAL_OUNCE_COST * (weight - 1); System.out.println("Cost: " + costInCents + " cents"); } else { System.out.println("Use parcel post or priority mail"); } else { System.out.println("ERROR: Weight must be positive"); }

26 Programming and Problem Solving With Java 26 Dangling-else Problem  Arises only with nested if statements without braces  Example // For a score less than 70, displays "You need to improve" // For a score greater than 95, displays "Excellent work" // For a score between 70 and 95, displays nothing if (testScore >= 70)// Outer-if statement if (testScore > 95)// Inner-if statement System.out.println("Excellent work!"); else System.out.println("You need to improve");  Results

27 Programming and Problem Solving With Java 27 Dangling-else Problem  When compiler finds else clause  "The else always matches the closest, unfinished if statement" // For a score less than 70, displays "You need to improve" // For a score greater than 95, displays "Excellent work" // For a score between 70 and 95, displays nothing if (testScore >= 70)// Outer-if statement if (testScore > 95)// Inner-if statement System.out.println("Excellent work!"); else System.out.println("You need to improve");

28 Programming and Problem Solving With Java 28 Dangling-else Problem  Structure of a dangling else clause

29 Programming and Problem Solving With Java 29 Dangling-else Problem  How braces avoid the dangling- else problem

30 Programming and Problem Solving With Java 30 Multiway Choices

31 Programming and Problem Solving With Java 31 Multiway Choices: if-ladder char grade; if (score >= 90) { grade = 'A'; } else { if (score >= 80) { grade = 'B'; } else { if (score >= 70) { grade = 'C'; } else { if (score >= 60) { grade = 'D'; } else { grade = 'F'; } char grade; if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } rewrite nested if as if-ladder Nested if if-ladder

32 Programming and Problem Solving With Java 32 How the if-ladder Works

33 Programming and Problem Solving With Java 33 Multiway Choices: if-ladder  Default condition: last else in if-ladder  · Optional  Good idea to have one -- helps catch errors if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score < 60) { grade = 'F'; } else { System.out.println("Error in assignGrade"); } Missing cases for grades of C and D Default condition catches the error

34 Programming and Problem Solving With Java 34 General face() Method  Turtle graphics turnRight() -- turns relative degrees  No method to make turtle face absolute direction  Can use nested if to write face() myTurtle.face(122);  Direction of turtle can be anything  face(122) makes turtle face 122 degrees

35 Programming and Problem Solving With Java 35 General face() Method  Three cases to consider (c) The turtle may already be facing the desired direction

36 Programming and Problem Solving With Java 36 General face() Method  Three cases  need nested if statement  First version of face()  Handle case where turtle already facing desired direction // face: Faces the turtle an absolute direction, // from 1 to 360 degrees public void face(int degrees) throws TurtleException { // Make sure the turtle is not already facing the desired // direction if (this.direction() != degrees) { // Handle the other two cases here }  Must distinguish between the remaining two cases

37 Programming and Problem Solving With Java 37 General face() Method  Distinguish between two cases Current Direction < Desired Direction Current Direction > Desired Direction

38 Programming and Problem Solving With Java 38 General face() Method  Doesn't cross 0, current direction < desired  Second version of face() // face: Faces the turtle an absolute direction, // from 1 to 360 degrees public void face(int degrees) throws TurtleException { // Make sure the turtle is not already facing the desired // direction if (this.direction() != degrees) { if (this.direction() < degrees) { // The turtle doesn't cross 0 this.turn(degrees - this.direction()); } else { // The turtle crosses 0 }

39 Programming and Problem Solving With Java 39 General face() Method  Crosses 0, current direction > desired  Turn in two steps

40 Programming and Problem Solving With Java 40 General face() Method  Final version of face() // face: Faces the turtle an absolute direction, // from 1 to 360 degrees public void face(int degrees) throws TurtleException { // Make sure the turtle is not already facing the desired // direction if (this.direction() != degrees) { if (this.direction() < degrees) { // The turtle doesn't cross 0 this.turn(degrees - this.direction()); } else { // The turtle crosses 0 this.turn(360 - this.direction() + degrees); }

41 Programming and Problem Solving With Java 41 goPosition(): Example of if  Turtle graphics move() -- moves relative distance  No method to make turtle move to absolute position  Can use nested if to write goPosition() myTurtle.goPosition(10, 20); // row 10, column 20  Turtle can be anywhere on screen  Will move to upper left corner (facing same direction)

42 Programming and Problem Solving With Java 42 goPosition(): Example of if  Use helper methods  moveToRow()  moveToColumn();  First version of goPosition() // goPosition: Moves turtle to any absolute position on the // screen, without drawing a line. The // direction and pen status are unchanged. public void goPosition(int row, int column) throws TurtleException { this.moveToRow(row); this.moveToColumn(column); }

43 Programming and Problem Solving With Java 43 goPosition(): Example of if  Want pen status to be unchanged  Second version of goPosition() // goPosition: Moves turtle to any absolute position on the // screen, without drawing a line. The // direction and pen status are unchanged. public void goPosition(int row, int column) throws TurtleException { // Remember previous pen status boolean penDownAtBeginning = this.isPenDown(); if (this.isPenDown()) { this.penUp(); } this.moveToRow(row); this.moveToColumn(column); // Put pen back down if it was down before if (penDownAtBeginning) { this.penDown(); }

44 Programming and Problem Solving With Java 44 goPosition(): Example of if  Also want direction to be unchanged  Final version of goPosition() // goPosition: Moves turtle to any absolute position on the // screen, without drawing a line. The // direction and pen status are unchanged. public void goPosition(int row, int column) throws TurtleException { // Remember previous pen status and direction boolean penDownAtBeginning = this.isPenDown(); int previousDirection = this.direction(); if (this.isPenDown()) { this.penUp(); } this.moveToRow(row); this.moveToColumn(column); // Put pen back down if it was down before if (penDownAtBeginning) { this.penDown(); } // Restore previous direction this.face(previousDirection); }

45 Programming and Problem Solving With Java 45 goPosition(): Example of if  Need to write moveToRow(), moveToColumn()  Three cases in moveToRow()

46 Programming and Problem Solving With Java 46 goPosition(): Example of if  moveToRow(): Do nothing if already on desired row  First version of moveToRow() // moveToRow: Moves the turtle to an absolute row number. // Pen must be up beforehand, and is left // up afterward. The turtle's direction is // changed. // (This is a private method.) private void moveToRow(int row) throws TurtleException { // Make sure not on desired row if (row != this.atRow()) { // Handle the other two cases }

47 Programming and Problem Solving With Java 47 goPosition(): Example of if  moveToRow(): Use atRow() to tell direction to move  Second version of moveToRow() // moveToRow: Moves the turtle to an absolute row number. // Pen must be up beforehand, and is left // up afterward. The turtle's direction is // changed. // (This is a private method.) private void moveToRow(int row) throws TurtleException { // Make sure not on desired row if (row != this.atRow()) { // Handle the other two cases if (row < this.atRow()) { // Turtle below desired row } else { // Turtle above desired row }

48 Programming and Problem Solving With Java 48 goPosition(): Example of if  movePosition(): turtle is below desired row  Use face() to turn turtle straight up  Move from current row to desired row this.face(0); this.move(this.atRow() - row);  movePosition(): turtle is above desired row  Use face() to turn turtle straight down  Move from current row to desired row this.face(180); this.move(row - this.atRow()); Desired row

49 Programming and Problem Solving With Java 49 goPosition(): Example of if  Final version of moveToRow() // moveToRow: Moves the turtle to an absolute row number. // Pen must be up beforehand, and is left // up afterward. The turtle's direction is // changed. // (This is a private method.) private void moveToRow(int row) throws TurtleException { // Make sure not on desired row if (row != this.atRow()) { // Handle the other two cases if (row < this.atRow()) { // Turtle below desired row this.face(0); this.move(this.atRow() - row); } else { // Turtle above desired row this.face(180); this.move(row - this.atRow()); }

50 Programming and Problem Solving With Java 50 Boolean Operators & Expressions  Decisions often based on more than one factor  I will buy a new shirt if I like it AND it costs less than $25.  I will study in my room tonight if it's quiet there OR the library is closed.  Compound conditions in English  condition 1 AND condition 2  condition 1 OR condition 2  NOT condition

51 Programming and Problem Solving With Java 51 Boolean Operators & Expressions  The && (And) Operator  condition 1 && condition 2  True when both conditions are true  Example if (total >= 100 && total <= 500) { System.out.println("Error"); }  Displays error message if total between 100 and 500  Truth table  Tells result of any combination of true and false conditions

52 Programming and Problem Solving With Java 52 Boolean Operators & Expressions  The || (Or) Operator  condition 1 || condition 2  True when either condition is true (or both)  Example if (prizeNumber == 1234 || prizeNumber == 4321) { System.out.println("You won!"); }  Displays message if prizeNumber is 1234 or 4321

53 Programming and Problem Solving With Java 53 Boolean Operators & Expressions  The ! (Not) Operator  !condition  True when condition is false; false when condition is true  Good use: reverse a boolean method  Example with turtle graphics if (!myTurtle.isPenDown()) { myTurtle.penDown(); }  Example with characters if (!Character.isDigit(character)) { System.out.println("Not a digit"); }

54 Programming and Problem Solving With Java 54 Boolean Operators & Expressions  Short-circuit Evaluation: Stop evaluating ASAP  Example with && if (3 > 4 && x + y * z - 5 / 2.3 * 4 == 3.625) { System.out.println("Yes"); }  Example with || if (3 < 4 || x + y * z - 5 / 2.3 * 4 == 3.625) { System.out.println("Yes"); } EvaluateIgnore EvaluateIgnore

55 Programming and Problem Solving With Java 55 Boolean Operators & Expressions  Shortcuts that don't work

56 Programming and Problem Solving With Java 56 Boolean Operators & Expressions  Precedence Rules  ! very high  && and || after relational  && before ||  Examples if (!50 <= 100)... if (x < y && y < z || z == 0)... if (myTurtle.atRow() > 10 || myTurtle.atRow() < 40 && myTurtle.atColumn() > 5)

57 Programming and Problem Solving With Java 57 Boolean Operators & Expressions  Style Guidelines  Avoid the ! operator, except when reversing a the result of a Boolean variable or method.  Try to use no more than two or three Boolean operators in any expression.  When you use more than one Boolean operator in a single expression, use parentheses to make the expression clearer.

58 Programming and Problem Solving With Java 58 Boolean Operators & Expressions  DeMorgan's Laws  not ( a and b )  not a or not b  not ( a or b )  not a and not b  Use to distribute not over and or or  Example  "It's not both warm and sunny today."  "It's not warm or not sunny today." a b

59 Programming and Problem Solving With Java 59 ! Boolean Operators & Expressions  To avoid ! operator  Use DeMorgan's Laws if (!(a > b && c <= d))... rewrite as if (!(a > b) || !(c <= d))...  Use opposite relational operators if (!(a > b) || !(c <= d))... rewrite as if (a d)...

60 Programming and Problem Solving With Java 60 The switch Statement  Another multiway selection  Value of expresssion determines which statements executed switch (choice) { case 1: System.out.println(x + y); break; case 2: System.out.println(x * y); break; case 3: System.out.println(x - y); break; default: System.out.println("Invalid"); break; }

61 Programming and Problem Solving With Java 61 The switch Statement

62 Programming and Problem Solving With Java 62 The switch Statement  Restrictions on use  Expression (and all case values) must be integer or character  Each case is single literal or constant  Cases are distinct  More than one case value per statement group switch (choiceCharacter) { case 'A': // First style case 'a': System.out.println(x + y); break; case 'M': case 'm': // Second style System.out.println(x * y); break; }

63 Programming and Problem Solving With Java 63 The switch Statement  Choosing between if and switch  if: execute an optional group of statements  if-else: execute one of two groups of statements  switch: execute one of several groups of statements, based on integer-valued expression  nested-if: execute one of several groups of statements, based on arbitrary conditions  Nested-if is most general selection statement in Java  switch is easier to read than nested if

64 Programming and Problem Solving With Java 64 Errors  Error: mistake in the program  Sometimes called a bug  Almost always the fault of the programmer  Debugging: elimination of errors  Kinds of errors  Compile-time  Run-time  Logical

65 Programming and Problem Solving With Java 65 Errors: Compile-time  Compiler finds compile-time errors // Contains a compile-time error public class Welcome { System.out.println("Welcome to"); System.out.println("Java programming!"); }  Error message Welcome.java:5: Type expected. System.out.println("Welcome to"); ^ 1 error  Mistake in the use of the Java language  Similar to spelling error in English

66 Programming and Problem Solving With Java 66 Errors: Compile-time  Common compile-time errors  Leaving out a keyword  Putting a keyword where it doesn't belong  Leaving out a semicolon, comma, parenthesis or bracket  Misspelling a keyword or identifier  Easiest kind of error to fix  Two kinds of compile-time error  Syntax: error in form or structure if (amount == 3 || 6)... // Invalid expression  Semantic: error in meaning int intVariable = 3; System.out.println(floatVariable); // Unknown variable

67 Programming and Problem Solving With Java 67 Errors: Run-time  Computer finds when it runs the program import Keyboard; public class DivisionInto100 { public static void main(String[] args) throws java.io.IOException { int dividend, quotient; // Get the dividend from the user dividend = Keyboard.readInt("Enter the dividend: "); // Divide the dividend into 100 quotient = 100 / dividend; // Display the quotient System.out.println(quotient); }  Run program Enter the dividend: 0 java.lang.ArithmeticException: / by zero at DivisionInto100.main(DivisionInto100.java)

68 Programming and Problem Solving With Java 68 Errors: Run-time  Computer can't follow a program instruction  "Crash": when a program stops with a run-time error  Harder to fix than compile-time  Computer doesn't give the statement, just the method  Actual error may be much earlier in the program

69 Programming and Problem Solving With Java 69 Errors: Logical  Program compiles and runs, but output is wrong // Display the area of a rectangle import Keyboard; public class LogicalError { public static void main(String[] args) throws java.io.IOException { int length, height; length = Keyboard.readInt("Enter the length: "); height = Keyboard.readInt("Enter the height: "); System.out.println("The area is " + (length + height)); }  Run program Enter the length: 3 Enter the height: 4 The area is 7

70 Programming and Problem Solving With Java 70 Errors: Logical  Computer doesn't find the error  Up to programmer or user to notice something is wrong  No help from the computer in finding the cause  Hardest error to fix  Avoid logical errors!  Some features of Java help All variables must be defined All variables and parameters must have a type All variables must be initialized before use Objects and object-orientation  Best way to avoid: careful planning and design

71 Programming and Problem Solving With Java 71 Testing and Debugging Programs  Testing vs. debugging  Test: run with sample data to uncover errors  Debug: find the cause of a known error  Ideal testing strategy:  Run program using all possible inputs  Compare actual outputs to expected outputs  Problem: too many inputs  Program asks user for one integer: 4,294,967,296 inputs  Program asks user for two integers:18,446,744,073,709,551,616 inputs  Most programs require more input than this

72 Programming and Problem Solving With Java 72 Testing and Debugging Programs  Black-box Testing  Treat program as "black box"  Can only see inputs and outputs  Don't look at the code  Base test data on specifications: what the program is supposed to do Program to double input Test data = 2 Result = 4  ok

73 Programming and Problem Solving With Java 73 Testing and Debugging Programs  Black-box Testing  Too many inputs to test all  Use equivalence testing and boundary analysis  Group input values into equivalence classes  Equivalence class: input values the program should treat the same  Based on program's specifications  A few input values from each equivalence class should find almost 100% of errors  Can design test cases before writing code  Common practice in industry

74 Programming and Problem Solving With Java 74 Testing and Debugging Programs  Black-box Testing Example The program reads a test score as a single integer, and produces a letter grade as output. If the score is between 90 and 100 (inclusive), the program should display the grade A. If the score is between 80 and 89 (inclusive), the program should display the grade B. If the score is between 70 and 79 (inclusive), the program should display the grade C. If the score is between 60 and 69 (inclusive), the program should display the grade D. If the score is between 0 and 59 (inclusive), the program should display the grade F. The program should display an error message for any other score.  Equivalence classes

75 Programming and Problem Solving With Java 75 Testing and Debugging Programs  Boundary value  Values on and near boundary between equivalence classes  Choose typical value for each equivalence class, and three boundary values for each boundary

76 Programming and Problem Solving With Java 76 Testing and Debugging Programs  Glass-box Testing  Base test data on the code  Path coverage  Test every possible path  Most programs have too many paths to test  One if-else statement: 2 paths  20 if-else statements: > 1 million paths  Path coverage is not practical  Statement coverage  Make every statement execute at least once  Minimum amount of glass-box testing

77 Programming and Problem Solving With Java 77 Testing and Debugging Programs  Example 1 // Computes grades. (Wrong) 2 // This program reads a test score as a single integer, 3 // and produces a letter grade as output. If the score is 4 // between 90 and 100 (inclusive), the program should 5 // display the grade A. If the score is between 80 and 89 6 // (inclusive), the program should display the grade B. If 7 // the score is between 70 and 79 (inclusive), the program 8 // should display the grade C. If the score is between 60 9 // and 69 (inclusive), the program should display the grade 10 // D. If the score is between 0 and 59 (inclusive), the 11 // program should display the grade F. The program should 12 // display an error message for any other score. 13 14 import Keyboard; 15 16 public class GradeAssignment 17 { 18 public static void main(String[] args) 19 throws java.io.IOException 20 { 21 int score; 22 char grade = ' '; 23 24 System.out.println("--- Grade Assignment ---"); 25 score = Keyboard.readInt("Enter score: "); 26

78 Programming and Problem Solving With Java 78 Testing and Debugging Programs 27 if (score 100) 28 { 29 System.out.println("Score must be between 0 and 100"); 30 } 31 else if (score > 90 && score < 100) 32 { 33 grade = 'A'; 34 } 35 else if (score > 80 && score < 90) 36 { 37 grade = 'B'; 38 } 39 else if (score > 70 && score < 80) 40 { 41 grade = 'C'; 42 } 43 else if (score > 60 && score < 70) 44 { 45 grade = 'D'; 46 } 47 else 48 { 49 grade = 'F'; 50 } 51 52 System.out.println("Computed grade is " + grade); 53 } 54 }

79 Programming and Problem Solving With Java 79 Testing and Debugging Programs  Values that make every statement execute once Enter score: -50 Computed grade is F (should see error message) Enter score: 150 Computed grade is F (should see error message) Enter score: 95 Computed grade is A (OK) Enter score: 85 Computed grade is B (OK) Enter score: 75 Computed grade is C (OK) Enter score: 65 Computed grade is D (OK) Enter score: 50 Computed grade is F (OK)

80 Programming and Problem Solving With Java 80 Testing and Debugging Programs  Test boundary values Enter score: 0 Computed grade is F (OK) Enter score: 60 Computed grade is F (Should be D) Enter score: 70 Computed grade is F (Should be C) Enter score: 80 Computed grade is F (Should be B) Enter score: 90 Computed grade is F (Should be A) Enter score: 100 Computed grade is F (Should be A)

81 Programming and Problem Solving With Java 81 Testing and Debugging Programs  Fixes 27 if (score 100) 28 { 29 System.out.println("Score must be between 0 and 100"); 30 } 31 else if (score >= 90 && score <= 100) 32 { 33 grade = 'A'; 34 } 35 else if (score >= 80 && score < 90) 36 { 37 grade = 'B'; 38 } 39 else if (score >= 70 && score < 80) 40 { 41 grade = 'C'; 42 } 43 else if (score >= 60 && score < 70) 44 { 45 grade = 'D'; 46 } 47 else 48 { 49 grade = 'F'; 50 } 51

82 Programming and Problem Solving With Java 82 Conditional Operator

83 Programming and Problem Solving With Java 83 Artificial Intelligence  Study of  Making a computer sense its surroundings  Analyze what it finds  React to its findings  Goal  Get computers to do traditionally human tasks

84 Programming and Problem Solving With Java 84 Artificial Intelligence  Turing Test (Alan Turing, 1950)  Communication only by terminal  Person and computer try to convince interviewer they are human  If interviewer can't tell difference, computer has intelligence

85 Programming and Problem Solving With Java 85 Artificial Intelligence  Expert systems  Simulates the reasoning of a human expert with advanced knowledge in a particular area  Used in banking, finance, mining, medicine, geology  Natural language translation  Original goal for artificial intelligence  Difficult problem: incomplete specifications for natural languages Example: Time flies like an arrow  Today, computers can translate better, but not completely

86 Programming and Problem Solving With Java 86 Artificial Intelligence  Many expert systems based on production systems  Consist of  collection of states (including start and goal)  a collection of productions (rules)  a control system  Productions  Tell how to move from one state to another  Control system  Decides which production to use next  Goal of a production system  Move from the start state to the goal state

87 Programming and Problem Solving With Java 87 Artificial Intelligence  Heuristics  "Rules of thumb" - usually true, but not always  Used when "best" hard to find, and "good enough" will do  Example: Traveling salesperson problem  Visit a set of cities, each exactly once  What is the shortest route?  Only solution: examine all routes  2 x 10 32 possible routes  Examining 1 billion routes/sec, would take 8.4 x 10 13 centuries to examine them all  Heuristic to get "good enough" solution  Generate 2 billion random routes, take best of those

88 Programming and Problem Solving With Java 88 Artificial Intelligence  Heuristic for maze  Always examine paths facing goal first

89 Programming and Problem Solving With Java 89 Artificial Intelligence  Neural network: Simulation of human brain  Based on neurons  Electrical signals enter dendrites  Based on inputs, cell may send signal to other neurons through axon

90 Programming and Problem Solving With Java 90 Artificial Intelligence  Neural network  Simulated neuron is variable with weighted inputs and one output  If weighted sum of inputs > threshold, fire output value

91 Programming and Problem Solving With Java 91 Artificial Intelligence  Setting up a neural network  Connect neurons in some pattern  Choose threshold for each neuron  Choose weights for each connection  Training the network  Give the network sample input data and expected output  Network should "learn" how to process the input to give the expected output  Common use: examination of satellite photographs  Weather  Vegetation  Minerals


Download ppt "Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 4 Selection Control Statements The if Statement More About Selection Errors."

Similar presentations


Ads by Google