1 / 18

Selection as a Control Structure

Learn about control structures in Java, including selection statements, blocks within methods, and algorithmic approaches. Explore examples and practice problems to enhance your coding skills.

bjohnny
Download Presentation

Selection as a Control Structure

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. Selection as a Control Structure Control structures page 2The Calculator class with a client program page 3-5Blocks inside methods page 6The if statement has two forms page 7Curly braces and indents page 8Nested if and multiple choice statements page 9-10Decision tables page 11Boolean expressions page 12-13Comparing strings page 14-15Short-circuit evaluation page 16The switch statement page 17Comparing computed decimal numerals page 18 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  2. Control Structures • An algorithm is “a limited and ordered set of well-defined rules for solving a problem” (see chapter 2) • Three categories of execution order or controlstructures: • sequential (all client programs up to now) • selection (the if statement, this chapter) • loop (the while statement, see chapter 6) • Activitydiagrams illustrate control structures. a given order Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  3. Class Diagram and Two Possible Activity Diagrams for a Calculator object Calculator number1 number2 getNumber1 getNumber2 setNumbers calculateSum calculateDifference calculateProduct calculateQuotient Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  4. The Calculator Class public double calculateSum() { return number1 + number2; } public double calculateDifference() { return number1 - number2; } public double calculateProduct() { return number1 * number2; } public double calculateQuotient() { /* Division by zero gives special results: * Both numerator and denominator are 0: * Result: Double.NaN ("not-a-number") * Only denominator is 0: * Result: Double.NEGATIVE_INFINITY or * Double.POSITIVE_INFINITY. * Printing these values gives "NaN" and "Infinity". */ return number1 / number2; } } class Calculator { private double number1; private double number2; public Calculator(double initNumber1, double initNumber2) { number1 = initNumber1; number2 = initNumber2; } public double getNumber1() { return number1; } public double getNumber2() { return number2; } public void setNumbers(double newNumber1, double newNumber2) { number1 = newNumber1; number2 = newNumber2; } Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  5. import javax.swing.JOptionPane; class TestCalculator1 { public static void main(String[] args) { /* Reading data */ String number1Read = JOptionPane.showInputDialog("First number: "); String number2Read = JOptionPane.showInputDialog("Second number: "); double number1 = Double.parseDouble(number1Read); double number2 = Double.parseDouble(number2Read); int answer = JOptionPane.showConfirmDialog(null, "Add the numbers? ", "Calculator", JOptionPane.YES_NO_OPTION); /* Calculating results */ Calculator calcus = new Calculator(number1, number2); double calculatedAnswer; char operator; if (answer == JOptionPane.YES_OPTION) { // Yes is pressed calculatedAnswer = calcus.calculateSum(); operator = '+'; } else { // No or Esc is pressed, or the dialogue is closed calculatedAnswer = calcus.calculateDifference(); operator = '-'; } /* Printing results */ String result = "Our calculation: " + calcus.getNumber1() + " " + operator + " " + calcus.getNumber2(); result += "\nThe answer is " + calculatedAnswer; JOptionPane.showMessageDialog(null, result); System.exit(0); } } Client Program with Selection the selection has to be formulated as a yes/no question Solve problem 2, page 125. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  6. Blocks Inside Methods • Local variables are variables declared inside methods. • The scope of a local variable is the rest of the block where the variable is declared. • A method may contain many blocks inside each other. • Variables can be declared inside blocks. • As a recommended practice, variables should be declared near the place they are used. • An alternative calculator program is shown to the right. The scope of the variables is shown. Solve problem 2, pp. 132-133. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  7. The if Statement has Two Versions NB! Equality is written with two equality signs. [not (boolean expression)] [boolean expression] if (boolean expression) statement1else statement2 A boolean expression may be a boolean variable or a comparision, examples: a > 10 noOfGirls < noOfBoys noOfMen == noOfWomen [boolean expression] [not (boolean expression)] if (boolean expression) statement Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  8. Curly Braces and Indents if (boolean expression) statement1 else statement2 • If statement1 and/or statement2 consist of more than one individual statement, the statements have to be enclosed in curly braces {}. • Otherwise, it’s not necessary to use curly braces. However, for the sake of readability, and to decrease the chance of errors, we also recommend using curly braces if only one individual statement is to be executed and there isn’t room for it on the same line as if or else. • Example, we have discovered that b should be increased by 1 if a > b: • Starting point: Correction: if (a > b) if (a > b) sum += a; sum += a; b++; • Why isn't this "correction" correct? • Do you think the chance to get the code correct is higher if the starting point is as follows: • if (a > b) sum += a; If so, why? • Discussion / conclusion? Solve problem 2, page 136. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  9. Example: if (temperature > 0) { System.out.println( "Degrees above zero."); } if (temperature == 0) { System.out.println("Zero degrees."); } if (temperature < 0) { System.out.println("Degrees below zero."); } A few superfluous tests. Superfluous tests are removed: if (temperature > 0) { System.out.println("Degrees above zero."); } else { if (temperature == 0) { System.out.println("Zero degrees."); } else { System.out.println("Degrees below zero."); } // end of the innermost if-else statement } // end of the outermost if-else statement Or we could write: Nested if and Multiple-Choice Statements if (temperature > 0) System.out.println("Degrees above zero."); else if (temperature == 0) System.out.println("Zero degrees"); else System.out.println("Degrees below zero."); Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  10. int a = -10; int b = 20; if (a > 0) { if (b > 10) b = 10; } else a = 0; System.out.println(a + " " + b); a = -10; b = 20; if (a > 0) if (b > 10) b = 10; else a = 0; System.out.println(a + " " + b); What's the Difference between the Following Two Code Segments? If you use multiple if statements inside each other (nested if), and an else block doesn’t belong to the closest preceding if, it has to be marked with {}. Solve problem 2, page 144. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  11. Decision Tables • A grade is computed according to the following decisiontable: points grade 90-100 A 80-89 B 70-79 C 60-69 D 0-59 F • Problem: Complete the getGrade() method: class Grade { private int points; public Grade(int initPoints) { points = initPoints; } public int getGrade() { // negative value is returned if invalid no. of points .…fill inn what is missing..... } } Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  12. Boolean Expressions • A boolean expression has the value true or false. • The logical-complementoperator ! (also called the not-operator) reverses the expression’s value. !true is false and vice versa. • Boolean expressions are created using the comparisonoperators: < less than <= less than or equal to Examples: > greater than number > 10 >= greater than or equal to (price * number) != 100 != not equal to number1 + number2 == number3 + number4 == equal to • More complex expressions are created combining simple boolean expressions using the following two operators: && conditional-and (or only: “and”) || conditional-or (or only: “or”) • See operator summary, table 5.4, page 147. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  13. Calculating a Complex Boolean Expression a >= 0 && a <= 4 || a >= 10 && a <= 15 || a == 20 true false true false false a is equal to 16 false false false false Solve all problems, pp. 149-150. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  14. Comparing Strings • The String class offers methods to comparing strings. • Two strings are given: String name1 = "Margaret Eliza"; String name2 = "Maya"; • Using the equals() method: if (name1.equals(name2)) System.out.println("The names are the same."); else System.out.println("The names are not the same."); • Printout: The names are not the same. • Using the compareTo() method: int result = name1.compareTo(name2); if (result < 0) System.out.println(name1 + " comes first."); else if (result > 0) System.out.println(name2 + " comes first."); else System.out.println("The names are the same."); • Printout: Margaret Eliza comes first. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  15. Methods for Comparing Strings • The String class offers the following methods for comparing strings: • public int compareTo(String theOtherString) • public boolean equals(Object theOtherObject) • public boolean equalsIgnoreCase(String theOtherString) • public int compareToIgnoreCase(String theOtherString) • Comparing is according to the Unicode order. • The compareTo() methods returns a negative value if the string we’re sending the message to comes before theOtherString in the order, a positive value if it comes after, and 0 if the strings are equal. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  16. Short-Circuit Evaluation • Boolean expressions containing the operators && or || are calculated using short-circuitevaluation. • The computation is ended as soon as the result is determined. • If we have an && (”and”) operator between the expressions: • Continue the evaluation as long as the expressions are true. • The instant the Java interpreter encounters the first expression which evaluates to false, the compound expression as a whole will be false, and it can terminate the computation. • If we have an || (”or”) operator between the expressions: • Continue the evaluation as long as the expressions are false. • The instant one of them is true, the Java interpreter can stop, because then the whole expression is true. • An example: • if (number >= 0 && Math.sqrt(number) < limit) .... • In this example, the order of the comparisons cannot be swapped. If we do so, we risk trying to compute the square root of a negative number. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  17. String text = JOptionPane.showInputDialog("Which place? "); int place = Integer.parseInt(text); switch (place) { case 1: JOptionPane.showMessageDialog(null, "Gold!"); break; case 2: JOptionPane.showMessageDialog(null, "Silver!"); break; case 3: JOptionPane.showMessageDialog(null, "Bronze!"); break; case 4: /* falls through */ case 5: /* falls through */ case 6: JOptionPane.showMessageDialog(null, "You have points!"); break; default: int luckyNumber = (int) (100 * Math.random() + 1); JOptionPane.showMessageDialog(null, "Thank you for honourable achievement!\n" + "Your lucky number is: " + luckyNumber); break; } The switch Statement • If each instance in a multiple-choice statement corresponds to a specific numerical value or a character, it may be practical to use the switch statement. • See example to the right. • All the labels have to represent different constant expressions — in other words, separate values. Thus, it’s not possible to provide an interval or a list of values here. • Jump out of the switch block only through "break". Solve problem, page 152. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  18. Comparing Computed Decimal Numerals • What is the value of number3 after the following code segment is executed: double number1 = 1.0e20; double number2 = number1 + 1.0; double number3 = number2 - number1; • Answer: number3 is 0. • Why? • 1 + 1,0·1020 = 1,00000000000000000001·1020. • The double data type handles only approx. 15 significant digits. • The value 1 is loosed if we try to add it to the very large number. • Never use the operators == and != to compare results from calculations involving decimal numerals. • Instead, check that the difference between the numbers is less than a given tolerance (the size of the tolerance should be according to the numbers): final double tolerance = 0.00001; if (Math.abs(number1 - number2) < tolerance) { System.out.println("The numbers are almost the same."); } else System.out.println("The numbers are different."); remember using the absolute value! Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002The Research Foundation TISIP, http://tisip.no/engelsk/

More Related