[英]Having trouble with this java code - supposed to print and count number of heads and tails in a random coin toss
因此,正如標題所述,我必須使用一個類文件以及一個主要方法java文件,該文件將調用該類文件並打印出起始硬幣面以及40多個硬幣面翻轉。 我還需要有2個計數器來計算正面和反面的數量。 這是我的類文件和主方法文件的代碼。 我遇到的問題是,每當我運行它時,它總是打印出頭數為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);
}
}
請幫助,在此先感謝。
當前,您正在將CoinToss coin
對象與String值heads
,這就是為什么它始終進入else
部分的原因。
我可以看到您正在將當前擲硬幣的結果設置為sideUp
(這是String
)。 因此,您需要將其與if
的heads
進行比較。
if(coin.getSideUp().equals("heads")) { // getSideUp() returns the sideUp value
headsCount++;
} else {
tailsCount++;
}
您正在將答案分配給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++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.