The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Determine source "event" from 2 objects.

I am flipping two coins and the first coin that produces three HEADS in a row wins. The programme should terminate after a coin reaches this goal. And I want to know which coin it was and print a statement saying ie either Coin1 or Coin2 won the race. I can flip them OK and count to three with my two counters headCount1 and headCount2. Problem is I cant pinpoint which coin it was that actually won. Thanks for helping and here is my code:

//Coin.java//Represents a coin with two sides that can be flipped.publicclass Coin
{privatefinalint HEADS =0;privatefinalint TAILS =1;privateint face;//sets up the coin by flipping it initially.public Coin (){
flip();}//flips the coin by randomly choosing a face value.publicvoid flip (){
face =(int)(Math.random()*2);}//returns true if the current face of the coin is heads.publicboolean isHeads (){return(face == HEADS);}//returns the current face of the coin as a string.publicString toString(){String faceName;if(face == HEADS)
faceName ="Heads";else
faceName ="Tails";return faceName;}}

Re: Determine source "event" from 2 objects.

Fixing that problem should answer your question, but let us know if you need more help.

Edit: No, maybe not. Your logic is not right. You want to keep track of heads flipped but if a tail is flipped, then zero the headsFlipped count. Your current logic simply waits for 3 heads whether they're in a row or not. Rework the logic as I've suggested.

BTW: If you have errors, you should post them, exactly as they appear at your end, copied and pasted.

Re: Determine source "event" from 2 objects.

Well I got there. I printed the state of each headCount object at the bottom of the code. And it shows me which one attained 3 and which one didnt. I am happy with that too, I just wonder is there a smarter way of doing it?

Re: Determine source "event" from 2 objects.

Originally Posted by Junky

You could use an if statement: if coin1 has 3 heads print coin one wins else print coin two wins. Up for debate: should headCount be a instance variable of Coin?

I think I know what your saying. I should write a method in the Coin class, something like public void headCount () and declare headCount as a variable?
How do I write a method in the Coin class to determine the value of the headCount? My if else statements that calculate it are in the FlipRace class ...