Modified From

Modified From

<p> Modified from: http://www.minich.com/education/wyo/java/lecture_notes/random.php</p><p>0613acaf29715a6d0629303f757d5f21.docx</p><p>The static method named random in the Math class can be used to create a random decimal value that is greater than or equal to 0.0 and less than 1.0. double x = Math.random(); // returns a double 0.0 <= x < 1.0</p><p>Math.ramdom can be multiplied by a constant to change the range: x = Math.random() * 6; // 0 <= x < 6 such as 0.11, 3.21, 5.99 x = Math.random() * 10; // 0 <= x < 10 such as 2.15, 7.73, 9.99</p><p>Casting the result to an integer is used to produce whole number values: num = (int) (Math.random() * 5); // 0, 1, 2, 3, 4 num = (int) (Math.random() * 2); // 0 or 1 num = (int) (Math.random() * 2) + 1; // 1 or 2 num = (int) (Math.random() * 8) + 1; // 1, 2, 3, 4, 5, 6, 7, 8 num = (int) (Math.random() * 10) - 4; // -4 <= num <= 5 </p><p>Notice the general form:</p><p>(int) (Math.random() * howManyNums) + startingNum;</p><p>Be careful to use the extra set of parentheses in the examples above since</p><p> num = (int) Math.random() * 6 + 1; // always equals one</p><p>Complete the method to return a random whole number between low and high (inclusive). public static int rollDice(int low, int high) {</p><p> return ______} Modified from: http://www.minich.com/education/wyo/java/lecture_notes/random.php</p><p>If you wanted something to occur based on a probability of say 40% you could use: double x = Math.random(); if (x < 0.4) { System.out.println("The event occurred."); } else { System.out.println("The event did not occur."); } </p><p>Be careful not to create a logic error when answering a question like the following. Write a method that returns "win", "lose", or "draw" each 1/3 of the time. public String gameOutcome() { if ((int) (Math.random() * 3) ) == 0) { return "win"; } else if ((int) (Math.random() * 3) ) == 1) { return "lose"; } return "draw"; }</p>

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    2 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us