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

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

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

Building Java Programs

Building Java Programs

Building Java Programs

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

assertion: A statement that is either true or false.

Building Java Programs

COMP 202 Java in one week

Building Java Programs

! 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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Chapter 2. Elementary Programming

Computer Components. Software{ User Programs. Operating System. Hardware

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

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

CSC 1214: Object-Oriented Programming

Computer Components. Software{ User Programs. Operating System. Hardware

Building Java Programs Chapter 5

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

An overview of Java, Data types and variables

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Accelerating Information Technology Innovation

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Java Programming. Atul Prakash

3. Java - Language Constructs I

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

DM550 Introduction to Programming part 2. Jan Baumbach.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

CS 112 Introduction to Programming

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

Welcome to CSE 142! Zorah Fung University of Washington, Spring Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

COMP 110 Programming Exercise: Simulation of the Game of Craps

A web-based IDE for Java

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Java Classes: Random, Character A C S L E C T U R E 6

You have seen abstractions in many places, lets consider them from the ground up.

CSCI 2101 Java Style Guide

Programming Lecture 3

Text processing. Readings: 4.4

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

ECE 122 Engineering Problem Solving with Java

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

2 rd class Department of Programming. OOP with Java Programming

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Introduction to Programming Using Java (98-388)

STUDENT LESSON A12 Iterations

Programming with Java

Program Fundamentals

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

TESTING AND DEBUGGING

DM503 Programming B. Peter Schneider-Kamp.

Welcome to CSE 142! Whitaker Brand. University of Washington, Winter 2018

Building Java Programs. Introduction to Programming and Simple Java Programs

Computational Expression

3. Java - Language Constructs I

Chapter 3. Selections

CS 302: Introduction to Programming

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

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

The MaSH Programming Language At the Statements Level

Software Practice 1 Basic Grammar

Lecture Set 2: Starting Java

CompSci 125 Lecture 02

CS 112 Introduction to Programming

Imports. Lexicon. Java/Lespérance 1. PROF. Y. LESPÉRANCE Dept. of Electrical Engineering & Computer Science

Lecture Set 2: Starting Java

Using Java Classes Fall 2018 Margaret Reid-Miller

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

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

Topic 12 more if/else, cumulative algorithms, printf

CEN 414 Java Programming

COP 3330 Final Exam Review

Computational Expression

CS 112 Introduction to Programming

CS 112 Introduction to Programming

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

Java Programming Language Mr.Rungrote Phonkam

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

c) And last but not least, there are javadoc comments. See Weiss.

Java Coding 3. Over & over again!

Chapter 2: Basic Elements of Java

Introduction to Java Unit 1. Using BlueJ to Write Programs

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

AP Computer Science A

Introduction to Java & Fundamental Data Types

Methods and Functions

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Question: Total Points: Score:

Variables. Data Types.

: Primitive data types Variables Operators if, if-else do-while, while, for. // // First Java Program. public class Hello {

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

Transcription:

Topic 16 Creating Correct Programs "It is a profoundly erroneous truism, repeated by all the copybooks, and by eminent people when they are making speeches, that we should cultivate the habit of thinking about what we are doing. The precise opposite is the case. Civilization advances by extending the number of operations which we can perform without thinking about them. Operations of thought are like cavalry charges in a battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments." -Alfred North Whitehead Based on slides for Building Java Programs by Reges/Stepp, found at http://faculty.washington.edu/stepp/book/ pp Odds and Ends 1

The keyword list thus far: 8 Complete list of Java keywords: abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized assert enum Odds and Ends 2

Generating "Random" Numbers Odds and Ends 3

The Random class 8Java has a class named Random whose objects generate pseudo-random numbers. Method name Description nextint() returns a random integer nextint(max) returns a random integer in the range [0, max) in other words, from 0 up through one less than the max nextdouble() returns a random real number in the range [0.0, 1.0) Example: Random rand = new Random(); int randomnumber = rand.nextint(10); // randomnumber has a random value between 0 and 9 Class Random is found in the java.util package. import java.util.*; Odds and Ends 4

Pseudo Random Numbers 8What does "pseudo random" numbers mean? 8Computers don't do things ambiguously despite what people e think 8They have a limited number of commands "Pick a random number" isn't one of them 8pseudo d random numbers are generated algorithmically via mathematical operations 8They start with an initial number of see number 8If you know the seed and the algorithm you can completely predict the sequence of numbers Odds and Ends 5

8Try this: Pseudo Random Numbers for(int i = 0; i < 10; i++){ Random r = new Random(1127); for(int j = 0; j < 20; j++){ System.out.print( r.nextint() ); System.out.println(); 8Try with out the initial seed. 8A whole area of computer science devoted to trying to generate seemingly random numbers Odds and Ends 6

Random examples Random rand = new Random(); 8A random number between 0 and 19 inclusive: 8A random number between 1 and 10 inclusive: 8A random number between 4 and 17 inclusive: 8A random even number between 0 and 10 inclusive: 8A random multiple of 10 between 100 and 200 inclusive: Odds and Ends 7

Random examples (answers) Random rand = new Random(); 8A random number between 0 and 19 inclusive: int random1 = rand.nextint(20); 8A random number between 1 and 10 inclusive: int random1 = rand.nextint(10) + 1; 8A random number between 4 and 17 inclusive: int random1 = rand.nextint(14) + 4; 8A random even number between 0 and 10 inclusive: int random1 = rand.nextint(6) * 2; 8A random multiple of 10 between 100 and 200 inclusive: int random1 = rand.nextint(11) * 10 + 100; Odds and Ends 8

Random practice problem 8Write a multiplication tutor program. Example dialogue: This program helps you learn multiplication by Asking you 5 random multiplication questions and counts how many you get right. #1 of 5: 10 * 25 = 250 Correct! #2 of 5: 72 * 12 = 864 Correct! #3 of 5: 87 * 21 = 1741 Incorrect. The correct answer was 1827 #4 of 5: 8 * 84 = 692 Incorrect. The correct answer was 672 #5 of 5: 25 * 36 = 900 Correct! You got 3 out of 5 Odds and Ends 9

The do/while Loop Odds and Ends 10

The do/while loop 8Java has another kind of loop named the do/while loop. It is almost identical to the while loop, except that its body statement(s) will always execute the first time, regardless of whether the condition is true. 8 The do/while loop, general syntax: do { <statement(s)> ; while (<condition>); Example: // roll until we get a number other than 3 Random rand = new Random(); int dice; do { dice = rand.nextint(); while (dice == 3); Odds and Ends 11

Creating Correct Programs and Reasoning About Programs Odds and Ends 12

8Bonus quote: Assertions "As soon as we started programming, we found out to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs." Maurice V Wilkes Odds and Ends 13

Assertions 8Assertion: A declarative sentence that is either true or false 8Examples: 2 + 2 equals 4 The Yankees did not play in the world series in 2006. x >45 It is raining. UT beat OU last year in football. UT volleyball will make the NCAA tourney this year. 8Not assertions How old are you? Take me to H.E.B. Odds and Ends 14

Assertions 8Some assertions are true or false depending di on context. Which of these depend on the context? t? 2 + 2 equals 4 The Yankees did not play in the world series in 2006. x > 45 It is raining. UT will beat OU next year. UT volleyball will make the NCAA tourney this year. Odds and Ends 15

Assertions 8Assertions that depend on context can be evaluated if the context is provided. when x is 13, x > 45 It was raining in Round Rock, at 8 am on, October 10, 2006. 8Many skills required to be a programmer or computer scientists 8Just a few we have seen so far ability to generalize create structured solutions trace code manage lots of details Odds and Ends 16

Assertions 8Another important t skill in programming and computer science is the ability "to make assertions about your programs and to understand the contexts in which those assertions will be true." Scanner console = new Scanner(System.in); System.out.print("Enter Y or N: "); String result = console.next(); // is result equal to "Y" or "N" here? Odds and Ends 17

Checking Input Scanner console = new Scanner(System.in); System.out.print("Enter Y or N: "); String result = console.nextline(); while(!result.equals("y") &&!result.equals("n")){ System.out.print( print("that wasn't a Y or N. "); System.out.print("Enter Y or N: "); result = console.nextline(); // is result equal to "Y" or "N" here? Odds and Ends 18

Assertions 8Provable Assertion: An assertion that t can be proven to be true at a particular point in program execution. 8Program Verification: A field of computer science that t involves reasoning about the formal properties of programs to prove the correctness of a program. Instead of testing. A number of UTCS faculty are involved in verification research: Hunt, Lam, Shmatikov, Young, Emerson, Moore, Odds and Ends 19

Examples if(<test>){ // test is always true here if(<test>){ // test is always true here else { // test is never true here if(<test>){ // test is always true here // other statements // can we assert test is true here? Odds and Ends 20

Examples if(<test>){ // test is always true here // more statements // can we assert anything about test here? while( <test> ){ //test is always true here // more statements // test is never true here (unless we break...) Odds and Ends 21

Examples if( x < 0 ){ // x < 0 is always true here x = -x; // what about x < 0 here? "Programmers use assertions naturally when writing programs. Program verification researchers try to figure out how to do this kind of reasoning in a formal, verifiable, and hopefully automated way." Odds and Ends 22

Example if(<test>){ // test is always true here if(<test>){ // test is always true here else { // test is never true here if(<test>){ // test is always true here // other statements // can we assert test is true here? Odds and Ends 23

Detailed Example public static void printcommonprefix(int x, int y){ int z = 0; // Point A while( x!= y ){ // Point B z++; // Point C if( x > y ){ // Point D x = x / 10; else { // Point E y = y / 10; // Point F // Point G System.out.println("common prefix = " + x); System.out.println("Number of digits discarded = " + z); Odds and Ends 24

Detailed Example 8Interested t t d in assertions: x > y x==y z == 0 8Are these assertions always true, never true, or sometimes true at the various labeled points in the method Odds and Ends 25

Assertion example 1 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(); nextint(); // Point D // Point E point(s) in the code? return count; next == 0 prev == 0 next == prev Which of the following assertions are true at which Choose ALWAYS, NEVER, or SOMETIMES. Odds and Ends 26

Assertion example 2 public static void mystery(int x, int y) { int z = 0; // Point A while (x >= y) { // Point B x -= y; // Point C z++; // Point D 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 E System.out.println(z + " " + x); Odds and Ends 27

Assertion example 3 // Assumes y >= 0, and returns x to the y power 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; y /= 2; // Point D else { // Point E prod *= x; y--; // Point F // Point G // Point H return prod; Which of the following assertions are true at which point(s) in the code? Choose ALWAYS, NEVER, or SOMETIMES. y == 0 y % 2 == 0 Odds and Ends 28

Java assert statement 8Java includes the ability to put assertions in the code as executable statements assert <boolean expression>; Odds and Ends 29