Building Java Programs

Similar documents
Building Java Programs

Type boolean. Building Java Programs. Recap: Type boolean. "Short-circuit" evaluation. De Morgan's Law. Boolean practice questions.

Building Java Programs

Building Java Programs

assertion: A statement that is either true or false.

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Building Java Programs Chapter 5

CS 112 Introduction to Programming

Text processing. Readings: 4.4

The keyword list thus far: The Random class. Generating "Random" Numbers. Topic 16

Topic 16. battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments." -Alfred North Whitehead

Text processing. Characters. The charat method. Fun with char! char vs. String. Text processing. Readings: 4.4 (pg ) 'h' is a char

Building Java Programs

CSc 110, Autumn Lecture 26: Assertions. Adapted from slides by Marty Stepp and Stuart Reges

Building Java Programs

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

1. An operation in which an overall value is computed incrementally, often using a loop.

Building Java Programs

Building Java Programs

NoSuchElementException 5. Name of the Exception that occurs when you try to read past the end of the input data in a file.

Building Java Programs

CS 112 Introduction to Programming. Exercise: MatchDB. match1. Removing break. Solution I: Using break. Loop Patterns: break; Fencepost.

Building Java Programs

CSE142 Sample Midterm Spring Name UW NetId (e.g. whitab) Section (e.g., AA) TA

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Midterm Examination (MTA)

Full file at

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp!

Building Java Programs

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

Loops. CSE 114, Computer Science 1 Stony Brook University

Java Coding 3. Over & over again!

CSE142 Sample Midterm, Winter 2018

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Midterm Review Session

Building Java Programs A Back to Basics Approach 4th Edition Reges TEST BANK Full download at:

AP Computer Science. if/else, return values. Copyright 2010 by Pearson Education

Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Topic 12 more if/else, cumulative algorithms, printf

Topic 11 Scanner object, conditional execution

CSE 142 Sample Midterm Exam #2

LECTURE 5 Control Structures Part 2

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Topic 12 more if/else, cumulative algorithms, printf

Advanced if/else & Cumulative Sum

Conditional Execution


Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Repetition, Looping. While Loop

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Topic 14 while loops and loop patterns

Example: Monte Carlo Simulation 1

Introduction. C provides two styles of flow control:

How would you handle the case for when a user selects an option? 1/15/2016 CSE 11 WINTER LEC 6 2

Returns & if/else. Parameters and Objects

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Chapter 2: Basic Elements of Java

Topic 11 Scanner object, conditional execution

Object Oriented Programming. Java-Lecture 6 - Arrays

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Final. Your Name CS Fall 2014 December 13, points total Your Instructor and Section

Chapter 4: Control Structures I

What two elements are usually present for calculating a total of a series of numbers?

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Control Flow Practice Problems Mr. Fahrenbacher AP Computer Science A

Building Java Programs

CIS 110: Introduction to Computer Programming

Last Class. While loops Infinite loops Loop counters Iterations

Example Program. public class ComputeArea {

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

CSE 142 Sample Midterm Exam #3

Lesson 7 Part 2 Flags

Full file at

Chapter 3. Selections

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

Controls Structure for Repetition

CSE 142, Autumn 2011 Midterm Exam: Friday, November 4, 2011

Decisions: Logic Java Programming 2 Lesson 7

Loops. GEEN163 Introduction to Computer Programming

CONDITIONAL EXECUTION

Combined Assignment Operators. Flow of Control. Increment Decrement Operators. Operators Precedence (Highest to Lowest) Slide Set 05: Java Loops

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Chapter 5 Lab Methods

CSE 142, Autumn 2007 Midterm Exam, Friday, November 2, 2007

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CIS November 14, 2017

CIS 1068 Netflix Challenge New assignment posted soon Lab grades November 14, 2017

Transcription:

Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1

The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's { body will run at least once. do { statement(s); while (test); // Example: prompt until correct password is typed String phrase; do { System.out.print("Type your password: "); phrase = console.next(); while (!phrase.equals("abracadabra")); 2

do/while question Modify the previous Dice program to use do/while. 2 + 4 = 6 3 + 5 = 8 5 + 6 = 11 1 + 1 = 2 4 + 3 = 7 You won after 5 tries! 3

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; // one roll 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!"); 4

break break statement: Immediately exits a loop. Can be used to write a loop whose test is in the middle. The loop's test is often changed to true ("always repeat"). while (true) { statement(s); if (test) { break; statement(s); break is considered to be bad style by some programmers. 5

Sentinel loop with 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); 6

Assertions reading: 5.5 7

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. The capital of North Dakota is Bismarck. 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. 8

Reasoning about assertions Suppose you have the following code: if (x > 3) { // Point A x--; else { // Point B x++; // Point C // Point D What do you know about x's value at the three points? Is x > 3? Always? Sometimes? Never? 9

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? (SOMETIMES) // Point D: is number < 0.0 here? (NEVER) 10

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

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 12

"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. 13

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

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

Assertion example 3 // Assumes y >= 0, and returns x^y public static int pow(int x, int y) { int prod = 1; // Point A while (y > 0) { // Point B if (y % 2 == 0) { // Point C x = x * x; y = y / 2; // Point D else { // Point E prod = prod * x; y--; // Point F // Point G return prod; Which of the following assertions are true at which point(s) in the code? Choose ALWAYS, NEVER, or SOMETIMES. Point A Point B Point C Point D Point E Point F Point G y > 0 y % 2 == 0 SOMETIMES SOMETIMES ALWAYS SOMETIMES ALWAYS ALWAYS ALWAYS SOMETIMES ALWAYS NEVER SOMETIMES ALWAYS NEVER ALWAYS 16