Building Java Programs

Similar documents
Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

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

Building Java Programs Chapter 5

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.

! 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

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

CS 112 Introduction to Programming

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

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

Text processing. Readings: 4.4

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

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

Building Java Programs

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

Topic 11 Scanner object, conditional execution

Building Java Programs

COMP 110 Programming Exercise: Simulation of the Game of Craps

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

Topic 11 Scanner object, conditional execution

CSc 110, Spring 2018 Lecture 9: Parameters, Graphics and Random. Adapted from slides by Marty Stepp and Stuart Reges

Topic 12 more if/else, cumulative algorithms, printf

AP Computer Science Unit 1. Programs

Topic 12 more if/else, cumulative algorithms, printf

Computational Expression

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

Java Coding 3. Over & over again!

Building Java Programs

Building Java Programs

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

UNIT 9A Randomness in Computation: Random Number Generators

Chapter 2: Basic Elements of Java

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

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

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Building Java Programs

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

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

CS 112 Introduction to Programming

CSE 142, Autumn 2008 Midterm Exam, Friday, October 31, 2008

private static final char[] Alphabet = "abcdefghijklmnopqrstuvwxyz".tochararray();

Controls Structure for Repetition

H212 Introduction to Software Systems Honors

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Advanced if/else & Cumulative Sum

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


Control Flow Practice Problems Mr. Fahrenbacher AP Computer Science A

Returns & if/else. Parameters and Objects

Lesson 7 Part 2 Flags

Programming with Java

CS 112 Introduction to Programming

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

Object-Based Programming. Programming with Objects

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

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

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

CSE 142 Sample Midterm Exam #2

CSE142 Sample Midterm Autumn 2018

Chapter 3. Selections

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

Building Java Programs

Midterm Examination (MTA)

Chapter 4: Control Structures I

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

Multiple Choice Using Object Methods

Selection and Repetition Revisited

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.

Computational Expression

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

Lecture 8 " INPUT " Instructor: Craig Duckett

Object Oriented Programming. Java-Lecture 6 - Arrays

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Building Java Programs

Introduction to Computer Science Unit 4B. Programs: Classes and Objects

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Chapter 4: Conditionals and Recursion

CS1083 Week 2: Arrays, ArrayList

Assignment 2.4: Loops

CSE142 Sample Midterm, Winter 2018

Lab Activity Plan. John Dalbey CPE /30/2013

Introduction to Computer Programming

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

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

COMP 110/L Lecture 4. Kyle Dewey

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

This exam is open book. Each question is worth 3 points.

Lecture Set 2: Starting Java

AP Computer Science Java Mr. Clausen Program 6A, 6B

Decisions: Logic Java Programming 2 Lesson 7

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

Transcription:

Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6 1

http://xkcd.com/221/ 2

Randomness Lack of predictability: don't know what's coming next Random process: outcomes do not follow a deterministic pattern (math, statistics, probability) Lack of bias or correlation (statistics) Relevant in lots of fields Genetic mutations (biology) Quantum processes (physics) Random walk hypothesis (finance) Cryptography (computer science) Game theory (mathematics) Determinism (religion) 3

Pseudo-Randomness Computers generate numbers in a predictable way using a mathematical formula Parameters may include current time, mouse position In practice, hard to predict or replicate True randomness uses natural processes Atmospheric noise (http://www.random.org/) Lava lamps (patent #5732138) Radioactive decay 4

The Random class A Random object generates pseudo-random numbers. Class Random is found in the java.util package. import java.util.*; Method name nextint() nextint(max) Description returns a random integer returns a random integer in the range [0, max) in other words, 0 to max-1 inclusive nextdouble() returns a random real number in the range [0.0, 1.0) Example: Random rand = new Random(); int randomnumber = rand.nextint(10); // 0-9 5

Generating random numbers Common usage: to get a random number from 1 to N int n = rand.nextint(20) + 1; // 1-20 inclusive To get a number in arbitrary range [min, max] inclusive: name.nextint(size of range) + min Where size of range is (max - min + 1) Example: A random integer between 4 and 10 inclusive: int n = rand.nextint(7) + 4; 6

Random questions Given the following declaration, how would you get: Random rand = new Random(); A random number between 1 and 47 inclusive? int random1 = rand.nextint(47) + 1; A random number between 23 and 30 inclusive? int random2 = rand.nextint(8) + 23; A random even number between 4 and 12 inclusive? int random3 = rand.nextint(5) * 2 + 4; 7

Random and other types nextdouble method returns a double between 0.0-1.0 Example: Get a random GPA value between 1.5 and 4.0: double randomgpa = rand.nextdouble() * 2.5 + 1.5; Any set of possible values can be mapped to integers code to randomly play Rock-Paper-Scissors: int r = rand.nextint(3); if (r == 0) { System.out.println("Rock"); else if (r == 1) { System.out.println("Paper"); else { // r == 2 System.out.println("Scissors"); 8

Random question Write a program that simulates rolling two 6-sided dice until their combined result comes up as 7. 2 + 4 = 6 3 + 5 = 8 5 + 6 = 11 1 + 1 = 2 4 + 3 = 7 You won after 5 tries! 9

Random 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 = 0; while (sum!= 7) { // roll the dice once int roll1 = rand.nextint(6) + 1; int roll2 = rand.nextint(6) + 1; sum = roll1 + roll2; System.out.println(roll1 + " + " + roll2 + " = " + sum); tries++; System.out.println("You won after " + tries + " tries!"); 10

Random question Write a program that plays an adding game. Ask user to solve random adding problems with 2-5 numbers. The user gets 1 point for a correct answer, 0 for incorrect. The program stops after 3 incorrect answers. 4 + 10 + 3 + 10 = 27 9 + 2 = 11 8 + 6 + 7 + 9 = 25 Wrong! The answer was 30 5 + 9 = 13 Wrong! The answer was 14 4 + 9 + 9 = 22 3 + 1 + 7 + 2 = 13 4 + 2 + 10 + 9 + 7 = 42 Wrong! The answer was 32 You earned 4 total points 11

Random answer // Asks the user to do adding problems and scores them. import java.util.*; public class AddingGame { public static void main(string[] args) { Scanner console = new Scanner(System.in); Random rand = new Random(); // play until user gets 3 wrong int points = 0; int wrong = 0; while (wrong < 3) { int result = play(console, rand); if (result == 0) { wrong++; else { points++; // play one game System.out.println("You earned " + points + " total points."); 12

Random answer 2... // Builds one addition problem and presents it to the user. // Returns 1 point if you get it right, 0 if wrong. public static int play(scanner console, Random rand) { // print the operands being added, and sum them int operands = rand.nextint(4) + 2; int sum = rand.nextint(10) + 1; System.out.print(sum); for (int i = 2; i <= operands; i++) { int n = rand.nextint(10) + 1; sum += n; System.out.print(" + " + n); System.out.print(" = "); // read user's guess and report whether it was correct int guess = console.nextint(); if (guess == sum) { return 1; else { System.out.println("Wrong! The answer was " + total); return 0; 13

Building Java Programs Chapter 5 Lecture 5-4: Assertions reading: 5.5 14

Punchline to a longer comic: http://www.smbc-comics.com/index.php?db=comics&id=2362#comic 15

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

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? 17

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) 18

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

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 20

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

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 22

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 23

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 SOMETIMES Point B ALWAYS Point C ALWAYS Point D ALWAYS Point E ALWAYS y > 0 y % 2 == 0 Point F SOMETIMES ALWAYS Point G NEVER SOMETIMES SOMETIMES ALWAYS SOMETIMES NEVER ALWAYS 24