基于头部或尾部的硬币翻转总价值

时间:2015-11-15 22:02:30

标签: java class if-statement constructor boolean

首先,是的,我已经研究过这个问题。是的,我见过类似的事情,并且没有任何问题,但这是一个额外的转折,我有点困惑。所以这就是我要做的事情:

  

对于循环的每次迭代,抛出所有硬币。如果硬币出现   然后将硬币的值添加到余额中。如果有硬币来   然后从尾标中减去硬币的价值。后   所有迭代,显示余额和所用的秒数   执行格式化为三位小数的循环。

Coin.java

import java.util.Random; 

public class Coin
{

private String sideUp;
private Random headORtail = new Random();

public Coin() //no-arg constructor to determine what side of the coin is facing up
{
toss(); //calls the toss method
}



public Coin(String whatSide) //parameterized constructor to set initial side of coin 
{
sideUp = whatSide;
}



public void toss() //simulates coin toss
{
int num = headORtail.nextInt(2); //random number in the range of 0 - 1

if(num == 0)
{
sideUp = "Heads"; //0 for heads
}
else
{
sideUp = "Tails"; //1 for tails
}

}



public String getSideUp() //returns value of sideUp
{
return sideUp;
}


}

CoinDemo.java     import java.util.Scanner;

public class CoinDemo
{
    public static void main(String[] args)
{

//uses parameterized constructor to allow the programmer to set the initial sideUp
Coin penny = new Coin("Tails"); 
//uses no-arg constructor to create coin objects
Coin nickel = new Coin(); 
Coin dime = new Coin();  
Coin quarter = new Coin();
Coin half = new Coin();
Scanner keyboard = new Scanner(System.in); //Creates a new scanner to allow user to enter input



System.out.println("Please enter the the number of coin flips to be performed.\nMust be greater than 0: ");
int numFlips = keyboard.nextInt();  //Stores the user input into numFlips



//Validation loop checks value entered
while (numFlips <= 0)
{
System.out.println("\n\t~~~ERROR~~~");
System.out.println("The number entered must be greater than 0, please try again.");
System.out.println("\t~~~~~~~~~~~\n");
    System.out.println("Please enter the the number of coin flips to be performed. Must be greater than 0: ");
    numFlips = keyboard.nextInt(); //stores the user input into numFlips
}



long totalTime = System.currentTimeMillis(); //Once valid number is entered start the timer

double totalCoin;



for (int i = 0; i < numFlips; i++) //for loop to increment until equal to user entered numFlips
{     
//calls the Coin object's toss method and stores result in their respective instance variables
penny.toss();
nickel.toss();
dime.toss();
quarter.toss();
half.toss();



}

}
}

我的理解是,例如penny.toss();在循环中执行它将在实例变量penny中存储字符串“Heads”或“Tails”。所以我试着用

if (penny == "Heads") 
{
totalCoin += 0.01;
} 
else 
{
totalCoin -= 0.01;
}

我不知道怎么回事。我对编程很新,所以请理解我正在努力学习。这就是为什么我在这里寻求帮助以了解如何做到这一点。

1 个答案:

答案 0 :(得分:1)

我看到的第一件事是,当你比较字符串时,你应该做

if (penny.getSideUp().equals("Heads"))

而不是使用==。

此外,您需要比较sideUp变量,而不是您的类。