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

Similar documents
Building Java Programs

Building Java Programs

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

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

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

Text processing. Readings: 4.4

Chapter 2. Elementary Programming

COMP 202 Java in one week

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

3. Java - Language Constructs I

Topic 11 Scanner object, conditional execution

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

CS 112 Introduction to Programming

Sierpinski Valentine.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

CSC 1214: Object-Oriented Programming

JAVA Ch. 4. Variables and Constants Lawrenceville Press

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

Topic 11 Scanner object, conditional execution

Topic 16 boolean logic

CS 112 Introduction to Programming

Java Programming. Atul Prakash

Sierpinski Valentine. q Our journey of introducing conditionals

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

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Topic 13 procedural design and Strings

Topic 12 more if/else, cumulative algorithms, printf

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

Building Java Programs

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

CompSci 125 Lecture 02

Computational Expression

Building Java Programs

An overview of Java, Data types and variables

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

Topic 12 more if/else, cumulative algorithms, printf

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

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

Building Java Programs. Introduction to Programming and Simple Java Programs

Building Java Programs

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

DM550 Introduction to Programming part 2. Jan Baumbach.

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

3. Java - Language Constructs I

CSCI 2101 Java Style Guide

Advanced if/else & Cumulative Sum

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

Lecture 8: The String Class and Boolean Zen

Chapter 3. Selections

Chapter 1. Introduction to Computers and Programming. M hiwa ahmad aziz

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

assertion: A statement that is either true or false.

Building Java Programs Chapter 4

Accelerating Information Technology Innovation

Following is the general form of a typical decision making structure found in most of the programming languages:

A web-based IDE for Java

ECE 122 Engineering Problem Solving with Java

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

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

Building Java Programs

Topic 14 while loops and loop patterns

Midterm Review Session

Programming with Java

Java Coding 3. Over & over again!

COMP 110 Programming Exercise: Simulation of the Game of Craps

Lecture 1: Basic Java Syntax

CSS 161 Fundamentals of Compu3ng. Flow control (2) October 10, Instructor: Uma Murthy

Section 2.2 Your First Program in Java: Printing a Line of Text

Chapter 2: Basic Elements of Java

Java I/O and Control Structures

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

2 rd class Department of Programming. OOP with Java Programming

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

Introduction to C# Applications

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

Topic 21 arrays - part 1

Static Methods & Decomposition

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

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

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.

Software Practice 1 Basic Grammar

DM503 Programming B. Peter Schneider-Kamp.

Building Java Programs

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

Introduction to Programming Using Java (98-388)

About this exam review

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Lab5. Wooseok Kim

Fundamentals of Programming Data Types & Methods

Building Java Programs

Entering the world of Javatar

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

CS 302: Introduction to Programming

Transcription:

Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/ Topic 15 boolean methods and random numbers "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 of 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

Programming Terminology Binary digit, 1 or 0 Byte, 8 bits kilobyte, 1024 bytes (2 10 = 1024) megabyte, 2 20 bytes, 1,048,576 1,000,000 bytes in some contexts gigabyte, 2 30 bytes, 1,073,741,824 1,000,000,000 bytes in some contexts

compile Programming Terminology syntax error, compile error, runtime error, logic error high level language class object

More While Loops What is the base 2 representation of 67 10? A. 100011 B. 111111 C. 1000000 D. 2111 E. None of A-D are correct Write a method to convert a base 10 int to a base 2 String

The keyword list thus far: 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 CS305j Introduction to Computing Odds and Ends 5

Methods that are tests Some methods return logical values (true or false). A call to such a method is used as a <test> in a loop or if. Scanner console = new Scanner(System.in); System.out.print("Type your first name: "); String name = console.next(); if (name.startswith("dr.")) { System.out.println("Med school or PhD?"); else if (name.endswith("esq.")) { System.out.println("And I am Ted 'Theodore' Logan!");

String test methods Method equals(<str>) equalsignorecase(<str>) startswith(<str>) endswith(<str>) contains(<str>) Description whether two strings contain the same characters whether two strings contain the same characters, ignoring upper vs. lower case whether one contains other's characters at start whether one contains other's characters at end whether the given string is found within this one String name = console.next(); if (name.contains("prof")) { System.out.println("When are your office hours?"); else if (name.equalsignorecase(""maverick")) { System.out.println("You're grounded, young man!");

Strings question Prompt the user for two words and report whether they: "rhyme" (end with the same last two letters) alliterate (begin with the same letter) Example output: (run #1) Type two words: car STAR They rhyme! (run #2) Type two words: bare bear They alliterate! (run #3) Type two words: sell shell They alliterate! They rhyme! (run #4) Type two words: extra strawberry

Strings answer // Determines whether two words rhyme and/or alliterate. import java.util.*; public class Rhyme { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("Type two words: "); String word1 = console.next().tolowercase(); String word2 = console.next().tolowercase(); // check whether they end with the same two letters if (word2.length() >= 2 && word1.endswith(word2.substring(word2.length() - 2))) { System.out.println("They rhyme!"); // check whether they alliterate if (word1.startswith(word2.substring(0, 1))) { System.out.println("They alliterate!");

Random numbers reading: 5.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

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;

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;

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

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!

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

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.

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

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;