Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- For loops:
- for (int i = 0; i < 10; i++) {
- // Does something
- }
- 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
- i < 10 - This is the condition, the loop runs while this is true (sound familiar?)
- i++ - This is the change, adds one to i at the end of EVERY loop
- After all of that, we learned/relearned how to do random:
- int number = (int)(Math.random() * num + 1);
- Where num is our target (This will set number to a random number from 1-target)
- Ex: int number = (int)(Math.random() * 50 + 1); Will set number to a number from 1-50
- We rewrote the Guessing Game using for loops:
- Ask the user for a number, tell them if it is ==, <, or > the random target number from 1-100.
- Tell the user how many guesses they have left.
- We used for loops and random calculations to determine how many times a coin was flipped and landed on heads:
- AN ANSWER:
- public static void main(String[] args) {
- int heads = 0;
- flipCount = 10;
- for (int i = 1; i <= flipCount; i++) {
- int coin = (int)(Math.random() * 2 + 1);
- String result = "";
- if (coin == 1) {
- // Heads
- heads++;
- result = "heads";
- } else {
- result = "tails";
- }
- System.out.println("Flip #" + i + " resulted in: " + result);
- }
- System.out.println(heads + " heads out of " + flipCount + " flips. The percentage of heads is " + ((heads/(flipCount*1.0))*100)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement