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

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

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

Building Java Programs

Building Java Programs

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

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

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

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

Building Java Programs

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

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!

Midterm Review Session

Advanced if/else & Cumulative Sum

CSE142 Sample Midterm, Winter 2018

Topic 12 more if/else, cumulative algorithms, printf

Topic 11 Scanner object, conditional execution

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

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

Topic 12 more if/else, cumulative algorithms, printf

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

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

Topic 11 Scanner object, conditional execution

Returns & if/else. Parameters and Objects

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

Conditional Execution


Building Java Programs

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

Topic 14 while loops and loop patterns

Chapter 4: Control Structures I

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

Chapter 2: Basic Elements of Java

Object Oriented Programming. Java-Lecture 6 - Arrays

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

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

Repetition, Looping. While Loop

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

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

CSE 143 Lecture 10. Recursion

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

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.

Building Java Programs

CIS 110: Introduction to Computer Programming

Example Program. public class ComputeArea {

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

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

CSE 142 Sample Midterm Exam #3

Lesson 7 Part 2 Flags

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

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

Example: Monte Carlo Simulation 1

Tutorial 03. Exercise 1: CSC111 Computer Programming I

Decisions: Logic Java Programming 2 Lesson 7

CONDITIONAL EXECUTION

Control Flow Practice Problems Mr. Fahrenbacher AP Computer Science A

Chapter 5 Lab Methods

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

Last Class. While loops Infinite loops Loop counters Iterations

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

CIS November 14, 2017

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

2.2 - Making Decisions

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

CS 112 Introduction to Programming

Building Java Programs

Building Java Programs Chapter 4

Lecture 8 " INPUT " Instructor: Craig Duckett

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 1

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 2

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 3

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. The capital of North Dakota is Bismarck. Mr. Marty met a monkey. 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 4

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 5

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

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