Building Java Programs - courses.cs.washington.edu

Building Java Programs - courses.cs.washington.edu

Building Java Programs Chapter 5 Lecture 5-3: Assertions, do/while loops reading: 5.4 - 5.5 self-check: 22-24, 26-28 Copyright 2008 by Pearson Education 1 Logical assertions assertion: A statement that is either true or false. Examples: Java was created in 1995. The sky is purple. 23 is a prime number. 10 is greater than 20. x divided by 2 equals 7. (depends on the value of x) An assertion might be false ("The sky is purple" above), but it is still an assertion because it is a true/false statement. Copyright 2008 by Pearson Education

2 Reasoning about assertions Suppose you have the following code: if (x > 3) { // Point A x--; } else { // Point B x++; } // Point C What do you know about x's value at the three points? Is x > 3? Always? Sometimes? Never? Copyright 2008 by Pearson Education 3 Assertions in code We can make assertions about our code and ask whether they are true at various points in the code.

Valid answers are ALWAYS, NEVER, or SOMETIMES. System.out.print("Type a nonnegative number: "); double number = console.nextDouble(); // Point A: is number < 0.0 here? (SOMETIMES) while (number < 0.0) { // Point B: is number < 0.0 here? (ALWAYS) System.out.print("Negative; try again: "); number = console.nextDouble(); // Point C: is number < 0.0 here? } // Point D: is number < 0.0 here? Copyright 2008 by Pearson Education (SOMETIMES) (NEVER) 4 Reasoning about assertions Right after a variable is initialized, its value is known: int x = 3; // is x > 0? ALWAYS In general you know nothing about parameters' values:

public static void mystery(int a, int b) { // is a == 10? SOMETIMES But inside an if, while, etc., you may know something: public static void mystery(int a, int b) { if (a < 0) { // is a == 10? NEVER ... } } Copyright 2008 by Pearson Education 5 Assertions and loops At the start of a loop's body, the loop's test must be true: while (y < 10) { // is y < 10? ALWAYS ... } After a loop, the loop's test must be false: while (y < 10) { ... } // is y < 10? NEVER Inside a loop's body, the loop's test may become false:

while (y < 10) { y++; // is y < 10? SOMETIMES } Copyright 2008 by Pearson Education 6 "Sometimes" Things that cause a variable's value to be unknown (often leads to "sometimes" answers): reading from a Scanner reading a number from a Random object a parameter's initial value to a method If you can reach a part of the program both with the answer being "yes" and the answer being "no", then the correct answer is "sometimes". If you're unsure, "Sometimes" is a good guess. Often around 1/2 of the correct answers are "sometimes." Copyright 2008 by Pearson Education

7 Assertion example 1 public static void mystery(int x, int y) { int z = 0; // Point A while (x >= y) { // Point B x = x - y; // Point C z++; } } // Point D // Point E System.out.println(z); Copyright 2008 by Pearson Education Which of the following assertions are true at which point(s) in the code? Choose ALWAYS, NEVER, or SOMETIMES.

x < y x == y z == 0 Point A SOMETIMES SOMETIMES ALWAYS Point B NEVER SOMETIMES SOMETIMES Point C SOMETIMES

SOMETIMES SOMETIMES Point D SOMETIMES SOMETIMES NEVER Point E ALWAYS NEVER SOMETIMES 8 Assertion example 2 public static int mystery(Scanner console) {

int prev = 0; int count = 0; int next = console.nextInt(); // Point A while (next != 0) { Which of the following assertions are // Point B if (next == prev) { true at which point(s) in the code? // Point C Choose ALWAYS, NEVER, or SOMETIMES. count++; } prev = next; next == 0 prev == 0 next == prev next = console.nextInt(); SOMETIMES Point A SOMETIMES ALWAYS // Point D } SOMETIMES SOMETIMES Point B NEVER // Point E return count;

NEVER ALWAYS Point C NEVER } SOMETIMES Point D SOMETIMES NEVER Point E Copyright 2008 by Pearson Education ALWAYS SOMETIMES SOMETIMES 9 Assertion example 3 // Assumes y >= 0, and returns x^y public static int pow(int x, int y) { int prod = 1; }

Which of the following assertions are // Point A while (y > 0) { true at which point(s) in the code? // Point B Choose ALWAYS, NEVER, or SOMETIMES. if (y % 2 == 0) { // Point C y > 0 y % 2 == 0 x = x * x; y = y / 2; Point A SOMETIMES SOMETIMES // Point D SOMETIMES } else { Point B ALWAYS // Point E ALWAYS Point C ALWAYS prod = prod * x; y--; SOMETIMES Point D ALWAYS // Point F

} NEVER Point E ALWAYS } // Point G Point F SOMETIMES ALWAYS return prod; Copyright 2008 by Pearson Education Point G NEVER ALWAYS 10 while loop variations reading: 5.4 self-checks: #22-24 exercises: #6 Copyright 2008 by Pearson Education

11 The do/while loop do/while loop: Executes statements repeatedly while a condition is true, testing it at the end of each repetition. do { statement(s); } while (test); Example: // prompt until the user gets the right password String phrase; do { System.out.print("Password: "); phrase = console.next(); } while (!phrase.equals("abracadabra")); Copyright 2008 by Pearson Education 12 do/while flow chart How does this differ from the while loop? The controlled statement(s) will always execute the first

time, regardless of whether the test is true or false. Copyright 2008 by Pearson Education 13 do/while question Modify the previous Dice program to use do/while. Example log of execution: 2 + 3 + 5 + 1 + 4 + You 4 = 5 = 6 = 1 = 3 = won 6

8 11 2 7 after 5 tries! Modify the previous Sentinel program to use do/while. Is do/while a good fit for solving this problem? Copyright 2008 by Pearson Education 14 do/while answer // Rolls two dice until a sum of 7 is reached. import java.util.*; public class Dice { public static void main(String[] args) { Random rand = new Random(); int tries = 0; int sum; do { int roll1 = rand.nextInt(6) + 1; int roll2 = rand.nextInt(6) + 1; sum = roll1 + roll2;

System.out.println(roll1 + " + " + roll2 + " = " + sum); tries++; } while (sum != 7); System.out.println("You won after " + tries + " tries!"); } } Copyright 2008 by Pearson Education 15 break break statement: Immediately exits a loop. Can be used to write a loop whose test is in the middle. Such loops are often called "forever" loops because their header's boolean test is often changed to a trivial true. while (true) { statement(s); if (test) { break; } statement(s); } break is bad style! Do not use it on CSE 142 homework.

Copyright 2008 by Pearson Education 16 Sentinel loop with break A working sentinel loop solution using break: Scanner console = new Scanner(System.in); int sum = 0; while (true) { System.out.print("Enter a number (-1 to quit): "); int number = console.nextInt(); if (number == -1) { // don't add -1 to sum break; } sum = sum + number; // number != -1 here } System.out.println("The total was " + sum); Copyright 2008 by Pearson Education 17

Recently Viewed Presentations

  • Diction

    Diction

    Diction 1. Consider: Newts are the most common of salamanders. Their skin is a . lighted. green, like water in a sunlit pond, and rows of a very bright red dots line their backs.
  • Role of Raja Rammohun Roy Library Foundation and National ...

    Role of Raja Rammohun Roy Library Foundation and National ...

    Role of Raja Rammohun Roy Library Foundation and National Mission on Libraries in promoting public library system & service in India . presented by. Shri . Soumen. Sarkar. Deputy Director(II&M), RRRLF Knowledge for all at their doorsteps
  • CONCURRENT THROMBOANGIITIS OBLITERANS AND MOYAMOYA DISEASE: A RARE

    CONCURRENT THROMBOANGIITIS OBLITERANS AND MOYAMOYA DISEASE: A RARE

    The direct revascularization technique involves intracranial mobilization of a branch of the superficial temporal artery (STA) and forming a direct arterial anastomosis between the mobilized STA branch and the ipsilateral middle cerebral artery (MCA) along the superficial surface of the...
  • SWE 637: Logic Coverage

    SWE 637: Logic Coverage

    Every terminal symbol in a production is replaced by other terminal symbols. 2. Terminal Replacement. Every terminal and nonterminal symbol in a production is deleted. 3. Terminal and Nonterminal Deletion.
  • Présentation PowerPoint - Carleton University

    Présentation PowerPoint - Carleton University

    Rescue the poorlostbunnies!! Statistics Canada's servers are powered by magical bunnies. FUN FACT. Illustration of a Stats Can employee feeding answers to data questions to the magical bunnies to keep them happy and productive.
  • DOUBLE-BLIND PLACEBO-CONTROLLED HUMAN FETAL DOPAMINE CELL 1* 1

    DOUBLE-BLIND PLACEBO-CONTROLLED HUMAN FETAL DOPAMINE CELL 1* 1

    18F-dopa PET scans were done at North Shore University Medical Center before and 12 months after surgery. At the University of Colorado Health Sciences Center, mesencephalic tissue from four embryos 7 to 8 weeks post-conception was held in tissue culture...
  • PowerPoint-presentatie

    PowerPoint-presentatie

    Read the first page, look for: Caesura. Alliterative verse/words. Christian elements
  • Prevention of Significant Deterioration (PSD)/Nonattainment ...

    Prevention of Significant Deterioration (PSD)/Nonattainment ...

    Airshed may still experience actual increase if the site is "over-permitted," that is, allowables much higher than actuals. 30 TAC 116 defines Project Emissions Increase (PEI), which will govern our reviews. Rulemaking will be required to accommodate Pruitt memo.