English subtitles

← Throwing a Die - Intro to Java Programming

Get Embed Code
5 Languages

Showing Revision 6 created 07/02/2017 by Dejan Trajkovic.

  1. Let's use the random class to write a program that uses a loop to simulate
  2. tossing a 6 sided die 100 times. The die can come up 1, 2, 3, 4, 5, or 6. Write
  3. your program so that it prints the number of sixes that come up. You'll need to
  4. import java.util.Random to use a random generator. So then I can help you check
  5. your work. We're going to do a bit of a magic trick. Random generators can be
  6. seeded. What that means is you give them a number to start rolling from, and
  7. then they grow a pattern based on that seed. So the sequence they generate will
  8. look random, but if you create another random generator like this, they'll both
  9. generate the exact same sequence. So all you need to know about that for now,
  10. is to declare your random generator this way. Because the grading code will be
  11. expecting a sequence of numbers generated with this seed. If you're not sure
  12. what I'm talking about, and you're curious, stick around for a moment and I'll
  13. demo what this does. But feel free to skip to the quiz. My trusty code pad.
  14. I'll create and seed a random generator, and now I'll do the exact same thing,
  15. and make another one. Now if I ask the first generator for an int, I'll get 2.
  16. And if I ask the other generator for exactly the same thing, I will also get 2.
  17. I can do this again, and they still both agree. So while I'm getting random
  18. numbers out of this, The numbers are predictable, so we know what to expect and
  19. can help you debug your code.