Topic 15 boolean methods and random numbers "It

Topic 15 boolean methods and random numbers "It

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 Copyright Pearson Education, 2010Based on slides by Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/ Programming Terminology Binary digit, 1 or 0 Byte, 8 bits

Nibble, half a byte, 4 bits kilobyte, 1024 bytes (210 = 1024) megabyte, 220 bytes, 1,048,576 1,000,000 bytes in some contexts gigabyte, 230 bytes, 1,073,741,824 1,000,000,000 bytes in some contexts Programming Terminology compile syntax error, compile error, runtime error, logic error high level language class object More While Loops What is the base 2 representation of 6710? 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 boolean break byte case catch char class const continue assert

CS305j Introduction to Computing default do double else extends final finally float for goto enum if implements import instanceof int

interface long native new package Odds and Ends private protected public return short static strictfp super switch synchronized this throw

throws transient try void volatile while 5 Methods that are tests Some methods return logical values (true or false). A call to such a method is used as a 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 Description equals() whether two strings contain the same characters equalsIgnoreCase() whether two strings contain the same characters, ignoring upper vs. lower case startsWith() whether one contains other's characters at start endsWith()

whether one contains other's characters at end contains() 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.Random; Method name Description nextInt() returns a random integer nextInt() 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: .nextInt() + Where is ( - + 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 + 3 + 5 + 1 + 4 + You 4 = 5 = 6 = 1 = 3 = won 6 8 11 2 7 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; }

Recently Viewed Presentations

  • Presentation title

    Presentation title

    DSC lead, DataDiscovery . and visualization. Advanced Analytics . Competence Center. Predictive . maintenance. Big Data in Transport. Data Science. in Finance sector. Predictive . maintenance. Advanced Analytics . in Telecommunications. Over 4000 Members in BI / Big Data Analytics....
  • Restriction Endonucleases - Buffalo State College

    Restriction Endonucleases - Buffalo State College

    Restriction Endonucleases BIO450 Restriction Enzymes Enzymatic Activity Biological Role Diversity Recognition Sequence Digestion Conditions Typical Reaction Double Digest Class Project Computer Analysis Enzyme Activity Biological Role of RE Restriction Modification System -restriction enzymes are paired with methylases.
  • Práctica de subjuntivo: presente y pasado

    Práctica de subjuntivo: presente y pasado

    The following is a practice for tomorrow's quiz. You will have to determine whether the sentences need present subjunctive or past subjunctive. Then, fill in the blank with the correct conjugation. (There are a few irregulars.)
  • Official DOH PowerPoint Template

    Official DOH PowerPoint Template

    A Facility User must log into the PSRS to read the Determination, which will be located in the communication log for that event, and respond accordingly. There are usually comments from the event reviewer that should be reviewed and addressed...
  • ENERGY STAR Criteria for Clothes Washers Overview of

    ENERGY STAR Criteria for Clothes Washers Overview of

    ENERGY STAR Clothes Washer Criteria History 1987 - Congress passed the National Appliance Energy Conservation Act (NAECA) 1994 - First Federal clothes washer standard and test procedure adopted 1997 - ENERGY STAR program expanded to include residential clothes washers 2001...
  • T2E - Reducing lack of transport as a barrier to gaining ...

    T2E - Reducing lack of transport as a barrier to gaining ...

    T2E - Transport to Employment Reducing lack of transport as a barrier to gaining employment in rural communities Steve Wright [email protected]
  • 12 - storage.googleapis.com

    12 - storage.googleapis.com

    Neural crest cells form the dorsal root ganglia sensory neurons; axons grow into the dorsal aspect of the cord. Figure 12.28. White. matter. Neural tube. cells. Central. cavity. ... Contains spinal reflex centers. Spinal Cord: Protection. Bone, meninges, and CSF.
  • Indian Empires

    Indian Empires

    Caste System. Because the Aryans regarded the people they conquered as inferior. Castes (Jatis)- by occupation. Brahmins (priests) ... the strategic location of Southeast Asia in the global trade routes connecting China, India, and the Mediterranean.