Building Java Programs



Similar documents
Building Java Programs

Building Java Programs

Topic 11 Scanner object, conditional execution

Building Java Programs

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Elementary Statistics and Inference. Elementary Statistics and Inference. 16 The Law of Averages (cont.) 22S:025 or 7P:025.

Building Java Programs

Introduction to Java

Chapter 2: Elements of Java

Basics of Java Programming Input and the Scanner class

CS170 Lab 11 Abstract Data Types & Objects

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

The Normal Approximation to Probability Histograms. Dice: Throw a single die twice. The Probability Histogram: Area = Probability. Where are we going?

Iteration CHAPTER 6. Topic Summary

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

JAVA ARRAY EXAMPLE PDF

AP Computer Science Static Methods, Strings, User Input

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Arrays. Introduction. Chapter 7

AP Computer Science File Input with Scanner

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

The overall size of these chance errors is measured by their RMS HALF THE NUMBER OF TOSSES NUMBER OF HEADS MINUS NUMBER OF TOSSES

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Install Java Development Kit (JDK) 1.8

Line-based file processing

Ch. 13.3: More about Probability

Chapter 16: law of averages

Chapter 2 Introduction to Java programming

Term Project: Roulette

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Object-Oriented Programming in Java

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Sample CSE8A midterm Multiple Choice (circle one)

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

6.042/18.062J Mathematics for Computer Science. Expected Value I

Part I. Multiple Choice Questions (2 points each):

J a v a Quiz (Unit 3, Test 0 Practice)

Topic 16 boolean logic

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Beating Roulette? An analysis with probability and statistics.

Using Files as Input/Output in Java 5.0 Applications

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

13 File Output and Input

Building Java Programs

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

While and Do-While Loops Summer 2010 Margaret Reid-Miller

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Introduction to Programming

Classes and Objects. Agenda. Quiz 7/1/2008. The Background of the Object-Oriented Approach. Class. Object. Package and import

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

6.1. Example: A Tip Calculator 6-1

Betting systems: how not to lose your money gambling

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Programmierpraktikum

Arrays in Java. Working with Arrays

LOOPS CHAPTER CHAPTER GOALS

Statistics and Random Variables. Math 425 Introduction to Probability Lecture 14. Finite valued Random Variables. Expectation defined

java Features Version April 19, 2013 by Thorsten Kracht

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

This Method will show you exactly how you can profit from this specific online casino and beat them at their own game.

Chapter 20: chance error in sampling

More on Objects and Classes

Chapter 4. Probability Distributions

Lecture 13. Understanding Probability and Long-Term Expectations

Week 5: Expected value and Betting systems

Elementary Statistics and Inference. Elementary Statistics and Inference. 17 Expected Value and Standard Error. 22S:025 or 7P:025.

We rst consider the game from the player's point of view: Suppose you have picked a number and placed your bet. The probability of winning is

Introduction to Discrete Probability. Terminology. Probability definition. 22c:19, section 6.x Hantao Zhang

Section 6.1 Discrete Random variables Probability Distribution

Visit us at

Gaming the Law of Large Numbers

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

D06 PROGRAMMING with JAVA

AMS 5 CHANCE VARIABILITY

Inaugural Lecture. Jan Vecer

Building Java Programs

The New Mexico Lottery

if and if-else: Part 1

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Week 1: Review of Java Programming Basics

MA 1125 Lecture 14 - Expected Values. Friday, February 28, Objectives: Introduce expected values.

Chapter 4 Lecture Notes

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion

Probabilistic Strategies: Solutions

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Using Two-Dimensional Arrays

Introduction to Java Lecture Notes. Ryan Dougherty

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Programming and Data Structures with Java and JUnit. Rick Mercer

Stat 20: Intro to Probability and Statistics

Software Engineering Techniques

Probability and Expected Value

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Introductory Probability. MATH 107: Finite Mathematics University of Louisville. March 5, 2014

Computer Programming I

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Transcription:

Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1-5.2 self-check: #8-17 exercises: #3-6, 10, 12 videos: Ch. 5 #1-2 1

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 2

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: 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; 3

Random questions Given the following declaration, how would you get: Random rand = new Random(); A random number between 1 and 100 inclusive? int random1 = rand.nextint(100) + 1; A random number between 2 and 4 inclusive? int random2 = rand.nextint(3) + 2; A random number between 50 and 100 inclusive? int random3 = rand.nextint(51) + 50; 4

Random and other types nextdouble method returns a double between 0.0-1.0 Example: Get a random value between 2.0 and 6.0: double r = rand.nextdouble() * 4.0 + 2.0; Any finite 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 { System.out.println("Scissors"); 5

Random question Write a program that simulates rolling of 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! 6

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!"); 7

Random question Write a multiplication tutor program. Ask user to solve problems with random numbers from 1-20. The program stops after an incorrect answer. 14 * 8 = 112 Correct! 5 * 12 = 60 Correct! 8 * 3 = 24 Correct! 5 * 5 = 25 Correct! 20 * 14 = 280 Correct! 19 * 14 = 256 Incorrect; the answer was 266 You solved 5 correctly Last correct answer was 280 The last line should not appear if the user solves 0 correctly. 8

Random answer import java.util.*; // Asks the user to do multiplication problems and scores them. public class MultiplicationTutor { public static void main(string[] args) { Scanner console = new Scanner(System.in); Random rand = new Random();... // fencepost solution - pull first question outside of loop int correct = 0; int last = askquestion(console, rand); int lastcorrect = 0; // loop until user gets one wrong while (last > 0) { lastcorrect = last; correct++; last = askquestion(console, rand); System.out.println("You solved " + correct + " correctly"); if (correct > 0) { System.out.println("Last correct answer was " + lastcorrect); 9

Random answer 2... // Asks the user one multiplication problem, // returning the answer if they get it right and 0 if not. public static int askquestion(scanner console, Random rand) { // pick two random numbers between 1 and 20 inclusive int num1 = rand.nextint(20) + 1; int num2 = rand.nextint(20) + 1; System.out.print(num1 + " * " + num2 + " = "); int guess = console.nextint(); if (guess == num1 * num2) { System.out.println("Correct!"); return num1 * num2; else { System.out.println("Incorrect; the correct answer was " + (num1 * num2)); return 0; 10

A Big Deal Some reasons why computers have changed all of science, engineering, sociology, politics, economics, They can process tons of data quickly They can generate tons of data quickly Example: Roll dice 10 million times Data generation often requires simulating a process with randomness Because some things (e.g., dice rolls) are random Because some things (e.g., disease causes) may not be random, but it s the best guess we have X% probability of cancer if you smoke 11

Known vs. unknown solutions Sometimes mathematicians have discovered a formula that gives an exact answer to a probability problem Example: Probability two dice sum to 7 But for more complicated problems sometimes no human knows! Next best thing : Try it a lot of times and measure the result Use a computer because it s faster Can be easier and more convincing than the math even when a formula is known 12

Two Examples 1. Playing roulette with a particular betting strategy It turns out a formula exists (it s a random walk), but programming a simulation is easy And simulation handles can t bet more than you have 2. UrbanSim Simulating the inter-related effects of land use and transportation decisions, and their environmental impact Much more complicated than gambling! 13

Roulette conclusions Bet small to play longer Bet big to increase your chances of winning Best is all at once: 48.3% Can t bet more than you have rule leads to surprising results: Given $1000, better off betting $500 than $990 But more importantly, we learned all this from simulation! But always make sure your code is right! 14