如何为我的抛硬币模拟器创建硬币?
How do i create a coin for my coin flip simulator?
我为我的投币模拟器创建了我的硬币 class 但我有几个问题,我缺少什么让它翻转 20 次(或者这是我在程序中写的东西?)还有,如何在我的程序中创建 "Coin"?
到目前为止,这是 class...
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;
}
}
您缺少 main()
方法,该方法是 运行 您的代码作为应用程序所必需的。尝试以下操作:
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.");
}
}
我为我的投币模拟器创建了我的硬币 class 但我有几个问题,我缺少什么让它翻转 20 次(或者这是我在程序中写的东西?)还有,如何在我的程序中创建 "Coin"? 到目前为止,这是 class...
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;
}
}
您缺少 main()
方法,该方法是 运行 您的代码作为应用程序所必需的。尝试以下操作:
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.");
}
}