# Virtual Coin Flip

This topic is 1926 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

hey i am trying to make a virtual coin flip in java.  import java.util.Random; public class flip { int head = 0; int tail = 0; public static void main (String[] args){ double start = 0; double end = 1; double random = new Random().nextDouble(); double result = start + (random * (end - start)); System.out.println(result); if (result < 0.5){ System.out.println("head"); }else if (result > 0.5 && result < 1.0){ System.out.println("tail"); } } } 

currently i am trying to make the coin flip 10 times and display how much times heads and tails come out. However i cant use any loops so i know i have to call my if method 10x. i just don't know how to lay that out properly and make all the data from the 10 method calls print out. I know i got to store it in my filed variables and then have a system.out.println print out the number in heads and tails.

##### Share on other sites
i am trying to make the coin flip 10 times and display how much times heads and tails come out[/quote]
A loop would be an ideal way, but seeing as you can't use them, why not call 10 "if" statements in a row?

I didn't have a computer available that had Java development stuff on it, so I whipped up a small demo using C# (which is close enough to get the point). I don't know why you can't use a loop, but this is a really poor way of doing it.

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace flip_example { class Program { static void Main(string[] args) { Random random = new Random(); double start = 0; double end = 1; double result = start = (random.NextDouble() * (end - start)); Console.WriteLine(result.ToString()); //1 if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //2 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //3 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //4 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //5 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //6 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //7 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //7 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //9 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //10 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //Keep console window open. Console.ReadLine(); } } } 

##### Share on other sites

You can also wrap every thing you are doing into a function and call it multiple times:
import java.util.Random; public class flip { static Random random_generator; static void flip_once() { double random_number = random_generator.nextDouble(); System.out.println(random_number); if (random_number < 0.5) System.out.println("head"); else System.out.println("tail"); } public static void main (String[] args) { random_generator = new Random(); flip_once(); flip_once(); flip_once(); flip_once(); flip_once(); flip_once(); flip_once(); flip_once(); flip_once(); flip_once(); } } 

This is a much better way of doing it. I will second this.

##### Share on other sites
Of course! I think it was Disjkstra who said loops weren't technically required in a programming language because they could always be rewritten as recursive functions.

##### Share on other sites
This version is slightly more elegant:
import java.util.Random; public class flip { static Random random_generator; static void flip_coin(int repeat) { if ( repeat > 0) { double random_number = random_generator.nextDouble(); System.out.println(random_number); if (random_number < 0.5) System.out.println("head"); else System.out.println("tail"); flip_coin(repeat-1); // <-- This is the only change } } public static void main (String[] args) { random_generator = new Random(); flip_coin(10); } } Edited by alvaro

##### Share on other sites

This version is slightly more elegant:
import java.util.Random; public class flip { static Random random_generator; static void flip_coin(int repeat) { if ( repeat > 0) { double random_number = random_generator.nextDouble(); System.out.println(random_number); if (random_number < 0.5) System.out.println("head"); else System.out.println("tail"); flip_coin(repeat-1); // <-- This is the only change } } public static void main (String[] args) { random_generator = new Random(); flip_coin(10); } }

From a performance point of view a function call is more expensive than a comprising.
This piece of code will cause every run to have an additional function call to flip_coin with no result.
As why there is a guard condition on top this is only because if you would be silly enough to provide any value less than 1 it would just skip the function.

Less LOC's (Lines Of Code) doesn't mean it is more elegant just remember that. Edited by DARSC0D3

##### Share on other sites

From a performance point of view a function call is more expensive than a comprising.
This piece of code will cause every run to have an additional function call to flip_coin with no result.
[/quote]
Your performance point of view is more or less irrelevant here - performance will be dominated by the I/O performed in this function.

Less LOC's (Lines Of Code) doesn't mean it is more elegant just remember that.
[/quote]
Lines of code does not equate to elegance, of course. That said, I think that by removing an extra comparison alvaro's code is simpler to understand. An alternative that I think would be simpler in your code is to restructure the final condition like so:
 if(repeat > 1) { flip_coin(repeat - 1); } 
Avoiding the complex mutation expression in the condition makes the code much simpler, IMO.

##### Share on other sites

Your performance point of view is more or less irrelevant here - performance will be dominated by the I/O performed in this function.

I was merely explaining as why I choose to do it this way and of course in a small program you probably won't have to think about such things.

Lines of code does not equate to elegance, of course. That said, I think that by removing an extra comparison alvaro's code is simpler to understand. An alternative that I think would be simpler in your code is to restructure the final condition like so:
if(repeat > 1) {
flip_coin(repeat - 1);
}
Avoiding the complex mutation expression in the condition makes the code much simpler, IMO.

I agree with you on that it would have been better to write it out like this, but on recalling the function i still have to disagree.
In this example there is little cost of recalling the function, but just out of habit not having to call a function that could be costly
I would prefer to not call a function if not needed.

##### Share on other sites
Could you just have the constructor of your class flip the coin and print the results, and then in your static main member you just create an array of your class with 10 elements? No loops, only a single line of code in main().

##### Share on other sites
Java doesn't have value objects, so creating an array with 10 elements does not create 10 instances of the class.

##### Share on other sites
Thank you for all of the repose everyone. Another thing that i forgot to mention totally sorry is the only place i can use static is in the Public static void main method. Any where else is a No No. Thanks again.

##### Share on other sites

From a performance point of view a function call is more expensive than a comprising.
This piece of code will cause every run to have an additional function call to flip_coin with no result.

Your performance point of view is more or less irrelevant here - performance will be dominated by the I/O performed in this function.

Less LOC's (Lines Of Code) doesn't mean it is more elegant just remember that.
[/quote]
Lines of code does not equate to elegance, of course. That said, I think that by removing an extra comparison alvaro's code is simpler to understand. An alternative that I think would be simpler in your code is to restructure the final condition like so:
[...]
[/quote]

Yes, lines of code have nothing to do with it. I think it's inelegant to check for the termination condition in two places, and the decrement of the passed parameter for no good reason also rubs me the wrong way.

##### Share on other sites

i am trying to make the coin flip 10 times and display how much times heads and tails come out

A loop would be an ideal way, but seeing as you can't use them, why not call 10 "if" statements in a row?

I didn't have a computer available that had Java development stuff on it, so I whipped up a small demo using C# (which is close enough to get the point). I don't know why you can't use a loop, but this is a really poor way of doing it.

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace flip_example { class Program { static void Main(string[] args) { Random random = new Random(); double start = 0; double end = 1; double result = start = (random.NextDouble() * (end - start)); Console.WriteLine(result.ToString()); //1 if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //2 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //3 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //4 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //5 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //6 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //7 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //7 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //9 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //10 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //Keep console window open. Console.ReadLine(); } } } 
[/quote]

Hey bytetroll i took your advice here because this is what we are suppose to do for our exercise however the problem i am getting is when i create two if statements if just flips the coin once and when it lands on tails its output the number that is greater than 0.5 and says tail tail twice. when it lands on heads it outputs the number that is less than 0.5 and outputs heads heads.

 import java.util.Random; public class flip { int head = 0; int tail = 0; public static void main (String[] args){ double start = 0; double end = 1; double random = new Random().nextDouble(); double result = start + (random * (end - start)); System.out.println(result); if (result < 0.5){ System.out.println("head"); }else if (result > 0.5){ System.out.println("tail"); if (result < 0.5){ System.out.println("head"); }else if (result > 0.5){ System.out.println("tail"); } } } } 

##### Share on other sites

[quote name='ByteTroll' timestamp='1349940852' post='4989003']
i am trying to make the coin flip 10 times and display how much times heads and tails come out

A loop would be an ideal way, but seeing as you can't use them, why not call 10 "if" statements in a row?

I didn't have a computer available that had Java development stuff on it, so I whipped up a small demo using C# (which is close enough to get the point). I don't know why you can't use a loop, but this is a really poor way of doing it.

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace flip_example { class Program { static void Main(string[] args) { Random random = new Random(); double start = 0; double end = 1; double result = start = (random.NextDouble() * (end - start)); Console.WriteLine(result.ToString()); //1 if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //2 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //3 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //4 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //5 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //6 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //7 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //7 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //9 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //10 result = start = (random.NextDouble() * (end - start)); if (result < 0.5) { Console.WriteLine("Head"); } else if (result > 0.5 && result < 1.0) { Console.WriteLine("Tail"); } //Keep console window open. Console.ReadLine(); } } } 
[/quote]

Hey bytetroll i took your advice here because this is what we are suppose to do for our exercise however the problem i am getting is when i create two if statements if just flips the coin once and when it lands on tails its output the number that is greater than 0.5 and says tail tail twice. when it lands on heads it outputs the number that is less than 0.5 and outputs head once.

 import java.util.Random; public class flip { int head = 0; int tail = 0; public static void main (String[] args){ double start = 0; double end = 1; double random = new Random().nextDouble(); double result = start + (random * (end - start)); System.out.println(result); if (result < 0.5){ System.out.println("head"); }else if (result > 0.5){ System.out.println("tail"); if (result < 0.5){ System.out.println("head"); }else if (result > 0.5){ System.out.println("tail"); } } } } 
[/quote]

##### Share on other sites
The reason you are getting the same values over and over again is beacuse you are using "result" to compare, but you never change it's value. The value of "result" is initially set using the  double result = start + (random * (end - start)); 
but that is never going to get executed again (thus it is going to pick the value once and keep that value). You will need to call  result = start + (random * (end - start));  after every "if...elseif" statement.

See the example I posted. After every block I recall  result = start + (random * (end - start));  giving random a new value.

EDIT: I misread your reply, so above is only an idea of why I think you are getting the issue.
EDIT2: Opps, I meant giving "result" a new value. Not "random." Edited by ByteTroll

##### Share on other sites
ByteTroll is right. Also, the reason why you get "tail" twice and "head" only once is that you have your brackets wrong. The second set of comparisons will be executed only if the first one rolls a tail. (Look at the indentation!)

By the way, the nextDouble() function returns 0 <= x < 1. That means that 0.5 should be a tail. You don't handle it in your if, so it won't print anything if exactly 0.5 is rolled (the probability of it, as we know, is 1 to DOUBLE_VALUES_BETWEEN_0_AND_1, so it probably won't happen in testing, but it is a logic error and you could lose points in the test or introduce nasty bugs if you work with production code!). You could modify your else if to "result > 0.5" or (since you are guaranteed that result won't be bigger than 1) just modify it to "else".

Or, you know, you could just use something like
 void printRoll() { if ((new Random().nextInt(2))==0) System.out.println("HEADS"); else System.out.println("TAILS"); }  Edited by ifthen

##### Share on other sites
 if (result < 0.5){ System.out.println("head"); }else if (result > 0.5){ System.out.println("tail"); }else{ System.out.println("edge"); } 

;)

##### Share on other sites
guys i serious dont know what i am doing. wish we should use a Loop for this exercise. Sorry i know am such a noob at this. So far this is what i got  import java.util.Random; public class flip { int head = 0; int tail = 0; int result = 0; public static void main (String[] args){ double start = 0; double end = 1; double random = new Random().nextDouble(); double result = start + (random * (end - start)); System.out.println(result); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); result = start + (random * (end - start)); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); result = start + (random * (end - start)); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); result = start + (random * (end - start)); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); result = start + (random * (end - start)); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); result = start + (random * (end - start)); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); result = start + (random * (end - start)); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); result = start + (random * (end - start)); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); result = start + (random * (end - start)); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); result = start + (random * (end - start)); if (result < 0.5){ System.out.println("head"); }else{ System.out.println("tail"); } } } } } } } } } } } 

so now the code is print out heads once and tail 10x

thanks for the help ifthen i just don't see what you are talking about. the out put looks like this

0.38712937129983

if it lands on tails
0.78982312093821
tail
tail
tail
tail
tail
tail
tail
tail
tail
tail

##### Share on other sites
Pretend you are the computer and follow the flow of the program. You compute a random number once. Then, if it is less than 0.5 you print "head" and do nothing else, because the rest of the code is inside the else' block. If it is not less than 0.5, you print "tail" and make the comparison again, but without picking another random number. So you look at the number and, again, it is not less than 0.5. Etc.

You need to close the else' block right after printing "tail". You also need to assign a fresh random number between throws.

##### Share on other sites
alvaro is right. Allow me to demonstrate it another way. I'll read your program as the computer reads it.

 public static void main (String[] args){ double start = 0; double end = 1; double random = new Random().nextDouble(); //hey Random, assign some number between <0-1) to variable random double result = start + (random * (end - start)); //now assign 0 + (random * (1-0)) = 0 + (random * 1) = random to variable result System.out.println(result); //I will tell the user the value of vairable result //is result is smaller than 0.5 if (result < 0.5) { //block T //I will tell the user that it's a head System.out.println("head"); //there aren't any statements, so I'll just skip over the block B, there's nothing relevant there } //end of block T else { //block F //I will tell the user it's a tail System.out.println("tail"); //the programmer wants me to do something (compute another flip) more before I end... //wait... random, end and start probably didn't change, shouldn't the result be the same? //not my problem, i'll compute it result = start + (random * (end - start)); //the value of result is the same as before... whatever //so let's compare again! if (result < 0.5) { //I never get to this, the result is always smaller than 0.5 System.out.println("head"); //but if I did, I would see that there's nothing more and continue after the else branch }else{ //block F-F //yeah... we print it System.out.println("tail"); //ANOTHER TIME? This guy is crazy! result = start + (random * (end - start)); //and we compare! yes! if (result < 0.5){ //also never happens System.out.println("head"); }else{ //block F-F-F /*and comparing and comparing... and comparing*/ } // end of block F-F-F } //end of block F-F <-- this is where I WOULD continue from if the heads come the second time } //end of block F <-- this is where I continue from if the heads come the first time //this is where I stop! No more work for me! YEAH! }

Can you see what is wrong with the code?
1. If the heads come first time, the compiler prints "heads" and skips the whole else branch all down to end of the block F. Nothing else happens.
Solution: Remember, the parent block MUST be executed for the child block to be executed too. So just make all the ifs children of main() block! That way, they will be executed independently. You want to say to computer: "Flip the coin ten times and tell me the result after every flip." Instead, you are saying this: "Flip the coin and tell me the result. If it's tails, do the same thing once more. But flip the coin ten times at most." You must change the code to match its meaning.

2. The computer flips the coin only the first time. Remember, the act of flipping is
 random = new Random().nextDouble(); 
This code
 result = start + (random * (end - start)); 
just converts the result of flipping to another range (or the same range, in your case).

The computer just looks at the coin and says which side is up. But it doesn't flip the coin before checking it, so the result must be the same as before. (Variables, as is the case with coins, usually don't change the side lying up unless moved. ).
SOLUTION: This one is easy, flip the coin (random = new Random().nextDouble();) before checking.

Also, it would be better to do it with procedures, but you seem you need to grasp the meaning of blocks ({}) and ifs. And those are probably the most important flow control in your code, so learn them and love them!

EDIT: How do the code tags work? They don't accept line-breaks?
EDIT 2: Okay, got it. You can't start a code tag with a multi-line comment, or it will be displayed only on one line. Strange. Edited by ifthen

##### Share on other sites
I am not sure if you are still having issues with this assignment, but I got bored today and figured I would lend a final hand. I recoded my example in Java. I generally don't do peoples homework for them, but you have at least given it a shot. For future reference, however, I would look closely at what I have done and learn. Hope this helps.

 import java.util.Random; public class flip { public static void main(String[] args) { //Since these values never get changed, it is good practice to make them //final. final double start = 0; final double end = 1; //Declare this as an instantiation of Random, not a double. Random random = new Random(); //Set the initial value of the result variable. Notice how I use the //"random" object. Intead of using a double that has an initial value, //I generate a new value ("random.nextDouble()") double result = start + (random.nextDouble() * (end - start)); System.out.println(result); //First result check. if(result <= 0.5) { System.out.println("head"); } else { System.out.println("tail"); } //Generate a new value and shove it in the result variable. Same thing //as the first call. I use random to generate a new value. If I didn't //and just used a double, the double variable would still have the same //value I set in the beginning. result = start + (random.nextDouble() * (end - start)); //Second result check. if(result <= 0.5) { System.out.println("head"); } else { System.out.println("tail"); } //Generate a new value and shove it in the result variable. result = start + (random.nextDouble() * (end - start)); //Third result check. if(result <= 0.5) { System.out.println("head"); } //Generate a new value and shove it in the result variable. result = start + (random.nextDouble() * (end - start)); //Fourth result check. if(result <= 0.5) { System.out.println("head"); } else { System.out.println("tail"); } //Generate a new value and shove it in the result variable. result = start + (random.nextDouble() * (end - start)); //Fifth result check. if(result <= 0.5) { System.out.println("head"); } else { System.out.println("tail"); } //Generate a new value and shove it in the result variable. result = start + (random.nextDouble() * (end - start)); //Sixth result check. if(result <= 0.5) { System.out.println("head"); } else { System.out.println("tail"); } //Generate a new value and shove it in the result variable. result = start + (random.nextDouble() * (end - start)); //Seventh result check. if(result <= 0.5) { System.out.println("head"); } else { System.out.println("tail"); } //Generate a new value and shove it in the result variable. result = start + (random.nextDouble() * (end - start)); //Eighth result check. if(result <= 0.5) { System.out.println("head"); } else { System.out.println("tail"); } //Generate a new value and shove it in the result variable. result = start + (random.nextDouble() * (end - start)); //Ninth result check. if(result <= 0.5) { System.out.println("head"); } else { System.out.println("tail"); } //Generate a new value and shove it in the result variable. result = start + (random.nextDouble() * (end - start)); //Tenth result check. if(result <= 0.5) { System.out.println("head"); } else { System.out.println("tail"); } } }  Edited by ByteTroll

##### Share on other sites
Bytetroll got it almost right, although the else branch of the third result check is missing! That could lead to nasty bugs in your code (hey, why does it sometimes print 10 lines and sometimes just 9?), so fix it if you are going to use it. THAT is the reason why you shouldn't write programs copy-paste-style, if you have many same or almost same snippets in your program, you will at some point make a mistake when creating/editing it and the program will not work properly. So be wary of it and try to minimize it!

Also, it prints the result at start, so remove that line if you don't want to see that floating point number printed in your output.

If you cannot use the static keyword elsewhere than in main, you have to do either the ten ifs trick or use a class with recursive function (if anyone knows another approach, share your knowledge). That could look like this

 import java.util.Random; public class Coin { //Is the head upwards? protected boolean head; //Reference to random generator used. protected Random randomGenerator; //Init the coin to the init values Coin(boolean _head, Random _randomGenerator) { head = _head; randomGenerator = _randomGenerator; } //Flips the coin so it is heads 50% of time and tails 50% of time. void flip() { //notice that you can assign results of expressions to booleans head = randomGenerator.nextDouble() < 0.5; } //Prints the name of side that is upwards side void print() { if (head) System.out.println("head"); else System.out.println("tail"); } //Flips the coin repeat times and prints its upwards side after every flip void flipAndPrint(int repeat) { if ( repeat > 0) { flip(); print(); flipAndPrint(repeat-1); } } //and some other functions if necessary (e.g. getter of the upwards side) //Flips a coin and prints the result ten times. public static void main (String[] args) { Random randomGenerator = new Random(); //it doesn't matter if we choose heads or tails as the starting upwards side because it will be flipped anyway Coin coin = new Coin(true, randomGenerator); coin.flipAndPrint(10); } } 

Yeah, that's probably an overkill for now, but suppose that you would develop betting game software or something like that. Using ten ifs to flip ten coins would be rather unprofessional. (Of course you would be using for loops. But it is good practice in Java to split every non-simple task to a separate class - divide and conquer, so this applies a bit.)

##### Share on other sites

Bytetroll got it almost right, although the else branch of the third result check is missing! That could lead to nasty bugs in your code (hey, why does it sometimes print 10 lines and sometimes just 9?), so fix it if you are going to use it. THAT is the reason why you shouldn't write programs copy-paste-style, if you have many same or almost same snippets in your program, you will at some point make a mistake when creating/editing it and the program will not work properly. So be wary of it and try to minimize it!

Also, it prints the result at start, so remove that line if you don't want to see that floating point number printed in your output.

If you cannot use the static keyword elsewhere than in main, you have to do either the ten ifs trick or use a class with recursive function (if anyone knows another approach, share your knowledge). That could look like this

 import java.util.Random; public class Coin { //Is the head upwards? protected boolean head; //Reference to random generator used. protected Random randomGenerator; //Init the coin to the init values Coin(boolean _head, Random _randomGenerator) { head = _head; randomGenerator = _randomGenerator; } //Flips the coin so it is heads 50% of time and tails 50% of time. void flip() { //notice that you can assign results of expressions to booleans head = randomGenerator.nextDouble() < 0.5; } //Prints the name of side that is upwards side void print() { if (head) System.out.println("head"); else System.out.println("tail"); } //Flips the coin repeat times and prints its upwards side after every flip void flipAndPrint(int repeat) { if ( repeat > 0) { flip(); print(); flipAndPrint(repeat-1); } } //and some other functions if necessary (e.g. getter of the upwards side) //Flips a coin and prints the result ten times. public static void main (String[] args) { Random randomGenerator = new Random(); //it doesn't matter if we choose heads or tails as the starting upwards side because it will be flipped anyway Coin coin = new Coin(true, randomGenerator); coin.flipAndPrint(10); } } 

Yeah, that's probably an overkill for now, but suppose that you would develop betting game software or something like that. Using ten ifs to flip ten coins would be rather unprofessional. (Of course you would be using for loops. But it is good practice in Java to split every non-simple task to a separate class - divide and conquer, so this applies a bit.)

Oh dear! That was a copy and paste fail. As ifthen stated... that is why you do not write programs copy and paste style. I wrote one block and then copy and pasted; missing one. Sorry about that one. Thank you for catching that ifthen! Edited by ByteTroll