编译但不运行的Java程序

时间:2014-02-18 07:55:07

标签: java

我无法弄清楚程序无法运行的原因。第一部分代码是我创建的类,而第二部分是使用创建的类的程序。该程序的基本点是有一个抛硬币类,然后在程序中多次使用该类来玩游戏。游戏涉及将硬币翻转至季度镍币和硬币。如果硬币是头部,则硬币的值加到总数中,如果是尾部,则不添加任何东西。当总价达到1.00美元或更高时,游戏就会停止。如果总数正好是1.00美元,则用户获胜,如果用户没有输。

//CoinToss Class
import java.util.Random;
public class Coin
{
   private String sideUp;

   public void toss()
   {
      Random flip = new Random();
      if (flip.nextInt(2) == 0)
      {
         String Up;
         Up = "Tails";
         Up = sideUp;
      }
      else
      {
         String Up;
         Up = "Heads";
         Up = sideUp;
      }
     }

   public String getSideUp()
   {
      return sideUp;
   }
}

无法运行的程序:

public class CoinToss
{
   public static void main(String[] args)
   {
     double total = 0.00;
     while (total <= 1.00)
     {
         Coin quarter = new Coin();
         quarter.toss();
         String side1 = quarter.getSideUp();
         if (side1 == ("Heads"))
         {
        total += 0.25;
         }
         else
         {
            total += 0;
         }
         Coin dime = new Coin();
         dime.toss();
         String side2;
         side2 = dime.getSideUp();
         if (side2 == ("Heads"))
         {
            total += 0.10;
         }
         else 
         {
         total += 0;
         }
         Coin nickel = new Coin();
         nickel.toss();
         String side3;
         side3 = nickel.getSideUp();
         if (side3 == ("Heads"))
         {
            total += .05;
         }
         else
         {
            total += 0;
         }

         }
         if (total == 1.00)
         {
         System.out.printf("Balance: %$,.2f\n", total);
         System.out.println("You win!");
         }
         else 
         {
         System.out.printf("Balance: %$,.2f\n", total);
         System.out.println("You lose!");
         } 
      }
     }

2 个答案:

答案 0 :(得分:1)

使用字符串 等于() 方法比较字符串

 Instead of side1 == ("Heads")

使用

side1.equals("Heads") and side2.equals("Heads")

并更正如下:

  if (flip.nextInt(2) == 0)
  {        
     sideUp = "Tails";
  }
  else
  {        
     sideUp = "Heads";
  }

答案 1 :(得分:1)

更改您的硬币等级

public class Coin
{
private String sideUp;

public void toss()
{
    Random flip = new Random();
    if (flip.nextInt(2) == 0)
    {
        sideUp = "Tails";
    }
    else
    {
        sideUp = "Heads";
    }
}

public String getSideUp()
{
    return sideUp;
}
}

有效!!

如上所述,将字符串与.equals()或.equalsIgnoreCase()方法进行比较......