Building Java Programs

Similar documents
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

! 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

Building Java Programs

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

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

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

Topic 11 Scanner object, conditional execution

CS 112 Introduction to Programming

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

Building Java Programs

Topic 11 Scanner object, conditional execution

Building Java Programs

COMP 110 Programming Exercise: Simulation of the Game of Craps

Computational Expression

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

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

Chapter 4: Control Structures I

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

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

Java Coding 3. Over & over again!

Controls Structure for Repetition

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs

Lecture 4: Conditionals

Topic 12 more if/else, cumulative algorithms, printf

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Midterm Examination (MTA)

AP CS Unit 3: Control Structures Notes

Programming with Java

H212 Introduction to Software Systems Honors

AP Computer Science Unit 1. Programs

Computational Expression

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

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

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

Topic 12 more if/else, cumulative algorithms, printf

Returns & if/else. Parameters and Objects

CS 112 Introduction to Programming

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

Object Oriented Programming. Java-Lecture 6 - Arrays

Fundamentals of Programming Data Types & Methods

Assignment 2.4: Loops

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

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

Chapter 3. Selections

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

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

Chapter 2: Basic Elements of Java

Advanced if/else & Cumulative Sum

Text processing. Readings: 4.4

2.2 - Making Decisions

Object Oriented Programming. Java-Lecture 1

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Topic 16 boolean logic

Lesson 7 Part 2 Flags

Introduction to Computer Science Unit 2. Notes

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java

Object-Based Programming. Programming with Objects

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

CS1083 Week 2: Arrays, ArrayList

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

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

Introduction to Computer Programming

Building Java Programs

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

Building Java Programs

Java I/O and Control Structures

assertion: A statement that is either true or false.

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

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

Multiple Choice Using Object Methods

Lab Activity Plan. John Dalbey CPE /30/2013

Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes

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

static String usersname; public static int numberofplayers; private static double velocity, time;

UNIT 9A Randomness in Computation: Random Number Generators

Lecture 8 " INPUT " Instructor: Craig Duckett

Selection and Repetition Revisited

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

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

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

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Chapter 4: Conditionals and Recursion

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

RANDOM NUMBER GAME PROJECT

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

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.

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

CSC1590 Java Assignment 2-0. User Defined Classes

CS1150 Principles of Computer Science Loops (Part II)

1 Short Answer (15 Points Each)

Building Java Programs

Java I/O and Control Structures Algorithms in everyday life

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

Transcription:

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

http://xkcd.com/221/ 2

The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s); Example: int age = 1; while (age < 21) { // initialization // test System.out.println("No alcohol for you!"); age++; // update System.out.println("Welcome to the club!"); 3

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

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 5

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 6

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

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; 8

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

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! 10

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

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 12

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

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; 14

Type boolean boolean: A logical type whose values are true and false. A logical test is actually a boolean expression. Like other types, it is legal to: create a boolean variable pass a boolean value as a parameter return a boolean value from methods call a method that returns a boolean and use it as a test boolean lovescse = true; boolean isprof = name.contains("prof"); boolean minor = age < 21; 15