因此,正如标题所述,我必须使用一个类文件和一个主要方法java文件,它调用类文件并打印出起始硬币面,以及40多个硬币面翻转。我还需要有两个计数器来计数头数和尾数。下面是我的类文件和主方法文件的代码。我遇到的问题是,每当我运行它,它总是打印出,正面有0计数和尾部作为40计数。
类文件:
import java.util.Random;
public class CoinToss
{
private String sideUp;
public CoinToss()
{
Random randomNum = new Random();
int number = randomNum.nextInt();
if(number%2 == 0)
sideUp = "heads";
else
sideUp = "tails";
System.out.println(sideUp);
}
public void toss()
{
Random randomNum = new Random();
int number = randomNum.nextInt();
if(number%2 != 0)
{
sideUp = "heads";
}
else
{
sideUp = "tails";
}
System.out.println(sideUp);
}
public String getSideUp()
{
return sideUp;
}
}
主要方法文件
public class CoinTossDemo
{
public static void main(String[] args)
{
int headsCount = 0;
int tailsCount = 0;
System.out.print("The Starting side of the coin is: ");
CoinToss coin = new CoinToss();
System.out.println();
for(int x = 0; x < 40; x++)
{
System.out.print("The next side of the coin is: ");
coin.toss();
System.out.println();
if(coin.equals("heads"))
{
headsCount++;
}
else
{
tailsCount++;
}
}
System.out.println("The amount of heads that showed up is: " + headsCount);
System.out.println();
System.out.println("The amount of tails that showed up is: " + tailsCount);
}
}
请帮忙,谢谢。
发布于 2013-11-17 22:06:35
目前,您正在将CoinToss coin
对象与字符串值heads
进行比较,这就是为什么它总是指向else
部分的原因。
我可以看到,您正在将当前掷硬币的结果设置为sideUp
(即String
)。因此,您需要将其与heads
中的if
进行比较。
if(coin.getSideUp().equals("heads")) { // getSideUp() returns the sideUp value
headsCount++;
} else {
tailsCount++;
}
发布于 2013-11-17 22:10:38
您要将您的答案分配给side up属性,因此获取该值coin.getSideUp()
for (int x = 0; x < 40; x++)
{
System.out.print("The next side of the coin is: ");
coin.toss();
System.out.println();
if (coin.getSideUp().equals("heads")) // use the side up property
{
headsCount++;
}
else
{
tailsCount++;
}
}
https://stackoverflow.com/questions/20041144
复制