Advertisement
Sc2ad

Lecture Notes- 9/21/16

Sep 21st, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. For loops:
  2. for (int i = 0; i < 10; i++) {
  3. // Does something
  4. }
  5. int i = 0 - This is the initial value, a new variable to iterate through the loop, and we are calling it i and setting it to 0
  6. i < 10 - This is the condition, the loop runs while this is true (sound familiar?)
  7. i++ - This is the change, adds one to i at the end of EVERY loop
  8.  
  9. After all of that, we learned/relearned how to do random:
  10. int number = (int)(Math.random() * num + 1);
  11. Where num is our target (This will set number to a random number from 1-target)
  12. Ex: int number = (int)(Math.random() * 50 + 1); Will set number to a number from 1-50
  13.  
  14. We rewrote the Guessing Game using for loops:
  15. Ask the user for a number, tell them if it is ==, <, or > the random target number from 1-100.
  16. Tell the user how many guesses they have left.
  17.  
  18. We used for loops and random calculations to determine how many times a coin was flipped and landed on heads:
  19. AN ANSWER:
  20. public static void main(String[] args) {
  21. int heads = 0;
  22. flipCount = 10;
  23. for (int i = 1; i <= flipCount; i++) {
  24. int coin = (int)(Math.random() * 2 + 1);
  25. String result = "";
  26. if (coin == 1) {
  27. // Heads
  28. heads++;
  29. result = "heads";
  30. } else {
  31. result = "tails";
  32. }
  33. System.out.println("Flip #" + i + " resulted in: " + result);
  34. }
  35. System.out.println(heads + " heads out of " + flipCount + " flips. The percentage of heads is " + ((heads/(flipCount*1.0))*100)
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement