Java Program (Coin Flip simulation) - java

This is the code for FlipRace program which initiates a race between two coins. GOAL is a globally declared variable. Whichever coin reaches GOAL number of heads fastest wins. Below it is the code for the Coin class.
My problem is that if I put GOAL = 3 , that is whichever coin gets 3 heads fastest wins, it works ok. When I set GOAL = 4 , still it works ok. But something weird starts happening once I put GOAL > 4. Say I put GOAL = 7, still the final result comes only when one coin has registered 4 heads NOT 7.
// FlipRace.java
package nisarg;
public class FlipRace {
public static void main(String[] args){
final int GOAL = 6;
int count1=0,count2=0;
Coin myCoin1 = new Coin();
Coin myCoin2 = new Coin();
while(count1 < GOAL && count2 < GOAL){
myCoin1.Flip();
myCoin2.Flip();
System.out.print("Coin1 : " +myCoin1 +"\t");
System.out.println("Coin2 :"+myCoin2);
count1 = (myCoin1.isHeads())? count1+1 : 0;
count2 = (myCoin2.isHeads())? count2+1 : 0;
}
if(count2 < GOAL) {
System.out.println("Coin1 wins!!");
} else if(count1 < GOAL){
System.out.println("Coin2 wins!!");
}
else {
System.out.println("Its a tie!!");
}
}
}
// Coin.java
package nisarg;
import java.util.Random;
public class Coin {
private final int HEADS = 1;
private final int TAILS = 0;
private int face;
public Coin(){
Flip();
}
public void Flip(){
face = (int)(Math.random()*2);
}
public boolean isHeads(){
return(face == HEADS);
}
public String toString(){
String faceName;
if(face == HEADS){
faceName = "H";
}
else {
faceName = "T";
}
return faceName;
}
}

Related

unable to come up with a solution to use methods calls

I am working on a lab that requires me to return the number it flips it requires to get heads. I used a for loop, and a while loop but it appears that returning the method values along with the loops is not making the code runnable. I would appreciate the assistance. There are two pieces of codes, each different classes calling upon another class.
import java.util.*;
public class GVCoin {
// true for heads, false for tails
private boolean isHeads;
private int flips, heads;
private Random r;
public GVCoin() {
r = new Random();
heads = 0;
flips = 0;
isHeads = true;
}
public void flip() {
isHeads = r.nextBoolean(); // Flip the coin by randomly choosing true / false
flips++; // Increment flip count
if(isHeads){
heads++; // Increment heads count if current flip results in heads
}
}
public boolean isHeads() {
return isHeads; // Return true if coin is currently heads
}
public String toString() {
String str;
str = "Flips: " + flips + " Heads: " + heads + " isHeads: " + isHeads;
return str; // Return String representation of important values
}
public int numFlips() {
return flips; // Return number of total flips
}
public int numHeads() {
return heads; // Return number of total heads
}
public int numTails() {
return flips - heads; // Return number of total tails
}
public void setToHeads(boolean h) {
isHeads = h;
}
public GVCoin(int seed) { // Create the coin with a random seed
this();
r = new Random(seed);
}
}
public class TossingCoins {
public int flipForHeads(GVCoin coin, int goal) {
int i = 0;
do {
coin.flip();
i++;
} while (i < goal);
return i;
}
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVCoin coin = new GVCoin(15); // Create a GVCoin object with seed value 15
int numHeads = 100; // Desire 100 heads
int totalFlips;
totalFlips = game.flipForHeads(coin, numHeads);
System.out.println("Total number of flips for 100 heads: " + totalFlips);
}
}
I suggest you not to use seed when you create Random. If you do, the outcome will be always the same.
Here some working code. I removed some code you wrote which I thought not actually needed. Cheers!
class GVCoin {
private Random r;
public GVCoin() {
r = new Random();
}
public GVCoin(int seed) {
this();
r = new Random(seed);
}
public boolean flip() {
return r.nextBoolean();
}
}
public class TossingCoins {
public int flipForHeads(GVCoin coin, int goal) {
int count = 0;
int numberOfHeads = 0;
while (numberOfHeads < goal) {
count++;
boolean isHead = coin.flip();
if (isHead) {
numberOfHeads++;
}
}
return count;
}
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVCoin coin = new GVCoin();
int numberOfHeads = 5;
int totalFlips;
totalFlips = game.flipForHeads(coin, numberOfHeads);
System.out.println("Total number of flips for "+ numberOfHeads + " heads: " + totalFlips);
}
}
I managed to figure out the code. On the method call I simply formatted the code as follows:
int flips = 0;
while (coin.numHeads() < goal) {
coin.flip();
flips++ ;
}
return flips;

Can not figure out how to detect how many consecutive Heads in a Coin Flipper

I have a project I am working on in my java class and cannot figure out what a few lines of code.
The project consists of flipping a coin and using various methods to detect how many heads or tails as well as how many flips have occurred so far.
import java.util.*;
public class GVcoin{
// true for heads, false for tails
private boolean isHeads;
private int flips, heads;
private Random r;
//Create the coin
public GVcoin(){
r = new Random();
heads = 0;
flips = 0;
isHeads = true;
}
//Flip the coin by random choosing true / false
public void flip(){
isHeads = r.nextBoolean();
flips++;
if(isHeads){
heads++;
}
}
//return true if coin is currently heads
public boolean isHeads(){
return isHeads;
}
//return String representation of important values
public String toString(){
String str;
str = "Flips: " + flips + " Heads: " + heads + " isHeads: " + isHeads;
return str;
}
//return number of total flips
public int numFlips(){
return flips;
}
//return number of total heads
public int numHeads(){
return heads;
}
//return number of total tails
public int numTails(){
return flips - heads;
}
//Set the coin to heads (or tails) to start
public void setToHeads(boolean h){
isHeads = h;
}
//Create the coin with a random seed
public GVcoin(int seed){
this();
r = new Random(seed);
}
}
The problem I can not seem to figure out is in a different class called TossingCoins and is the method public int consecutiveHeads(GVcoin c, int goal)
public class TossingCoins {
public int countHeads(GVcoin c, int goal){
while(c.numHeads() != goal) {
c.flip();
}
return c.numFlips();
}
public int flipForTails(GVcoin c, int goal){
while(c.numTails() != goal) {
c.flip();
}
return c.numFlips();
}
public int consecutiveHeads(GVcoin c, int goal){
while(c.numHeads() != goal){
c.flip();
}
}
// This method creates a TossingCoins object and calls the method for testing
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVcoin c = new GVcoin();
int numHeads = game.countHeads(c, 100);
}
}
What I have tried so far is see if the numHeads is not equal to the goal of heads. Then if it is not equal to the number of heads(goal), I would set the flip to add one. Which wold count 1, 2, 3, 4, 5 and so on till it hits the amount flips needed to hit the number of heads(goal).

Eclipse java coin toss

I need help in order for the output to also show the toss count since now it only shows the tosses showing heads. Tails heads tails and so on until it gets three heads but it is supposed to also show the toss count.
import java.util.*;
public class Coinrolling {
public static void main(String[] args) {
Random rand = new Random();
boolean noConsecutive = true;
int flipCount = 0;
int randomFlip;
while (noConsecutive) {
randomFlip = rand.nextInt(2) + 1;
if (randomFlip == 1) {
System.out.println("heads");
flipCount++;
}else {
System.out.println("tail");
flipCount= 0;
}
if (flipCount == 3) {
noConsecutive = false;
}
}
}
}
You can add tossCount variable in the same way you already have flipCount. You can also simplify the while loop condition by checking flipCount:
Random rand = new Random();
int flipCount = 0;
int tossCount = 0;
while (flipCount != 3) {
int randomFlip = rand.nextInt(2) + 1;
tossCount++;
if (randomFlip == 1) {
System.out.println("heads");
flipCount++;
} else {
System.out.println("tail");
flipCount = 0;
}
}
System.out.print("tossed " + tossCount + " times");

How to count the occurrences of random instances

For example I have a programming assignment that wants me to make a coin class and a driver class that randomly flips a coin 40 times and then counts at the very end how many times it ends up heads and tails. Well I got the entire code so far it being:
public class driver {
public static void main(String[] args) {
coin myCoin = new coin();
System.out.println("Coin initially is " + myCoin.getSideUp());
for (int i = 0; i < 40; i++) {
myCoin.toss();
System.out.println("Coin is now " + myCoin.getSideUp());
}
}
}
public class coin {
protected String sideUp;
public coin() {
if (Math.random() < 0.5)
this.sideUp = "heads";
else
this.sideUp = "tails";
}
public void toss() {
if (Math.random() < 0.5)
this.sideUp = "heads";
else
this.sideUp = "tails";
}
public String getSideUp() {
return this.sideUp;
}
}
That's all done, but how do I count the instances of each heads or tails?
Count them as the tosses are made instead of at the end. If the assignment prohibits this, save the results to an array and count the results from the array at the end.
Just check and see if your coin is head or tail after each toss.
You could keep the counter for each status(head/tail) in an array like below:
Coin myCoin = new Coin();
System.out.println("Coin initially is " + myCoin.getSideUp());
int[] coinCount = new int[2];
for (int i = 0; i < 40; i++) {
myCoin.toss();
System.out.println("Coin is now " + myCoin.getSideUp());
if(myCoin.getSideUp().equals("heads")){
coinCount[0]++;
} else {
coinCount[1]++;
}
}
System.out.println("Heads: "+coinCount[0]);
System.out.println("Tails: "+coinCount[1]);

Battleship Project Problems

public class Basic
{
public static int numGuess;
public int guess;
public int numHits = 0;
private static int[] ships;
private boolean hitShip;
public static boolean shipSunk;
private int[]board = new int[5];
public Basic()
{
numGuess = 0;
hitShip = false;
shipSunk = false;
}
public static void setShips (int[] loc)
{
ships = loc;
}
public int Check(int z)
{
for(int cell : ships)
{
if(z == cell)
{
hitShip = true;
System.out.println("\nYou hit an enemy ship!");
numHits++;
numGuess++;
if(numHits == ships.length)
{
shipSunk = true;
System.out.println("\nYou sunk the enemy ship!");
System.out.println("the number of guesses it took you to sink the ship is " + numGuess/3);
break;
}
}
else
{
System.out.println("You've missed the enemy ship!");
}
}
return z;
}
}
So I've been working on this battleship project for school and i made this 1-D board for my game. So far i think I've got my code correct, but now i'm stuck. In my for each loop, since it checks my guess with each of the three values of my ship, it prints whether or not i hit the ship three different times everytime i guess. I'm trying to get my program just to print whether or not i hit the ship once everytime i guess.
import java.util.Scanner;
import java.util.Random;
public class BasicTester
{
public static void main(String[] args)
{
Basic shipp = new Basic(); //initalizes basic class
int ship = (int)(Math.random() * 5); // gives ship a random # between 1 - 5
int ship1;
int ship2;
int guess;
if(ship <= 2)
{
ship1 = ship + 1;
ship2 = ship + 2;
}
else
{
ship1 = ship - 1;
ship2 = ship - 2;
}
int[] locations = {ship, ship1, ship2};// sets array of locations
shipp.setShips(locations); // sets locations to ships in other class
Scanner guesss = new Scanner(System.in); // Scanner
do
{
System.out.println("\nTell me where the enemy ship is.");
guess = guesss.nextInt(); // gives guess the int from Scanner
int resultb = shipp.Check(guess); // puts the int guess through the check method
}
while(Basic.shipSunk == false);
}
}
Instead of having your
else
{
System.out.println("You've missed the enemy ship!");
}
Inside the loop, you should set a flag before the loop
hitIt = false;
Then, when you check against the three "ships", you can set this flag to "true" when you find a hit. Finally, check the flag after the loop. If it is still false, print your message.

Categories

Resources