Blankets_McGee Blankets_McGee - 2 months ago 30
Java Question

Java Coin Flip Program

I'm trying to write a simple coin flip program and was wondering if I could get some help. I am fairly new to Java and was simply trying to ask the user how many times they would like to flip the coin. here is my code:

package cointossing;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
/**
* Coin tossing class to simulate the flip of a coin
* with two sides; Heads and Tails.
*
* @author Alex Chapman ID:
*
*/
public class CoinTossing
{
public static String sideUp;
public static int number;

public void run()
{
try( Scanner input = new Scanner(in) )
{
out.print("Enter how many times you would like to flip the coin");
out.print("if you enter 0 the program quits");
int number = input.nextInt();
}
}


private static void coin()
{
Random rand = new Random();
int sideup = rand.nextInt(2);
if (sideup == 0)
{
sideUp = "heads";
}
else
{
sideUp = "tails";
}
}

public static String getsideup()
{
out.println(sideUp);
return sideUp;
}



public static void main(String[] args)
{
int hcount = 0;
int tcount = 0;
for (int i = 1; i <= number; i++)
{
coin();
if (getsideup().equals("heads"))
{
hcount++;
}
else
{
tcount++;
}
}
out.println("total heads = " + hcount + " total tails = " + tcount);
}
}


but when i run the program it skips over asking the user anything and just displays 0's because there is no number of times to flip the coin...i feel like im on the right track but im stuck...any help would be greatly appreciated..

Answer

Change your main method, like this:

public static void main(String[] args) 
    {
        int hcount = 0;
        int tcount = 0;
        Scanner sc = new Scanner(System.in);
        out.println("How many coin flips do you want?");
        int number = sc.nextInt();
        for (int i = 1; i <= number; i++) 
        {
            coin();
            if (getsideup().equals("heads")) 
            {
                hcount++;
            } 
            else 
            {
                tcount++;
            }
        }
        out.println("total heads = " + hcount + " total tails = " + tcount);
    }
Comments