I created my Coin class for my Coin toss simulator but I have a few questions, what am I missing to make it flip 20 times (or is that something I write in the program?) and also, how do I create a "Coin" in my program? Here's the class so far...
import java.util.Random;
import java.util.Scanner;
public class Coin
{
private String sideUp;
private int headCount;
private int tailCount;
private Random rand = new Random();
public void toss()
{
sideUp = "";
headCount = 0;
tailCount = 0;
Random rand = new Random();
//Get random value 0 or 1
int value = rand.nextInt(2);
if(value == 0 )
{
this.sideUp = "heads";
headCount++;
}
else
{
this.sideUp = "tails";
tailCount++;
}
}
public String getSideUp(String sideUp)
{
this.sideUp = "";
headCount = 0;
tailCount = 0;
return sideUp;
}
public int getHeadCount(int headCount)
{
this.sideUp = "";
this.headCount = 0;
tailCount = 0;
return headCount;
}
public int getTailCount(int tailCount)
{
this.sideUp = "";
this.headCount = 0;
this.tailCount = 0;
return tailCount;
}
}
You are missing a main()
method, which is necessary to run your code as an application. Try the following:
public class Coin {
// keep your original code...
public static void main(String[] args) {
Coin theCoin = new Coin();
for (int i=0; i < 20; ++i) {
theCoin.toss();
}
System.out.println("Coin was heads " + theCoin.getHeadCount() + " times.");
System.out.println("Coin was tails " + theCoin.getTailCount() + " times.");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.