# Virtual Coin Flip

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

## Recommended Posts

Hi. I'm also a beginner so I thought I'd share my solution. I'm stuck at how to count the flips without loops because I don't quite yet have a firm grasp of the Java utils.

I enjoyed this. Thanks to all!
 import java.util.Random; import java.util.Arrays; import java.util.Collections; public class Coin { public enum Side { heads, tails, edge }; public Coin() { _side = Side.edge; } public Coin(Side side) { _side = side; } public Coin(Random generator) { flip(generator); } public void flip(Random generator) { double value = generator.nextDouble(); if(value < 0.5 ) {_side = Side.heads;} else if(value > 0.5) {_side = Side.tails;} else {_side = Side.edge;} } public boolean equals(Coin other) { return _side == other._side; } public String toString() { return _side.toString(); } private Side _side; public static void main(String[] args) { Coin heads = new Coin(Side.heads); Coin tails = new Coin(Side.tails); Random rand = new Random(); Coin[] coins = new Coin[] { new Coin(rand), new Coin(rand), new Coin(rand), new Coin(rand), new Coin(rand), new Coin(rand), new Coin(rand), new Coin(rand), new Coin(rand), new Coin(rand) }; System.out.println(Arrays.toString(coins)); int numHeads = Collections.frequency(Arrays.asList(coins), heads); System.out.println("There are " + numHeads + " heads."); int numTails = Collections.frequency(Arrays.asList(coins), tails); System.out.println("There are " + numTails + " tails."); } } 

I encountered some challenges while finding the "right way"
- no easy way to "apply"
- countif/equality not working here
- *()&(SFHKJHSF(&(*&:>( code tags!! Edited by m3mb3rsh1p

##### Share on other sites
Eureka! I solved the "equals() method not working properly!" conundrum!
 public boolean equals(Object other) { final Coin c = (Coin)other; return _side == c._side; }  Edited by m3mb3rsh1p

##### Share on other sites
Hmm... that really isn't a solution. Suppose you pass an object of type Car (or something else) to the function. It throws a ClassCastException and if you don't have the try-catch blocks surrounding it, it leads to premature program termination (as it does if other is null, but that is usually expected behaviour). You should compare that other is of type Coin or a child of Coin either by surrounding with try-catch blocks for ClassCastException or like this.
 public boolean equals(Object other) { Class thisClass = this.getClass(); Class otherClass = other.getClass(); while (otherClass != thisClass) { otherClass = otherClass.getSuperclass(); if (otherClass == null) return false; } final Coin otherCoin = (Coin)other; return _side == otherCoin._side; } 

##### Share on other sites
i've seem to of got it working thank a lot for all the help everyone. Hopefully someday i will be just like you guys in the For Beginners section helping out a fellow noob.