1

我正在尝试用简单的 java 制作一个 cee-lo 程序。我只是在学习。但是,当我到达即时 w。(我为测试简化了它)它总是返回false。我似乎无法弄清楚为什么。它甚至显示正确的数据,但是当它比较它时它失败了。

public class ceeLo
{
  public static void main (String [] args)
  {
    Scanner scan= new Scanner (System.in);
    int [] die = new int [3];
    int answer;
    boolean roll = true;
    boolean qualifed;
    boolean instantW;
    boolean instantL;

    do
    {
      System.out.println("Roll the dice?");
      answer = scan.nextInt ();
      if (answer == 0)
        roll= false;
      else
      {
        int i;
        for (i = 0; i < die.length; i++)
        {
          die[i]= rollin();
          System.out.println(diceTxt(die[i]));  
        }

        qualifed = (qualify (die));
        System.out.println("Qualified = " + qualifed);
        instantW = (easyW (die));
        System.out.println("Instant win = " + instantW);
      }
    }
    while (roll);
  }

  // Generate random numbers for the roll
  public static int rollin ()
  {
    Random rand = new Random();
    int die= rand.nextInt(6);
    return die;
  }

  //Check if dice qualify with pair
  public static boolean qualify (int [] die)
  {
    boolean qualify;
    //Pair Qualifying roll
    if (die[0] == die[1] || die[0] == die[2] || die[1] == die[2])
      qualify = true;
    else
      qualify = false;
    return qualify;
  }

  //Check if instant win 
  public static boolean easyW (int [] die)
  {
    boolean instantW;
    // show contents of die [x] for testing
    System.out.println (die[0] + "" + die[1] + "" + die[2]);
    if (die[0] > 2 && die [1] > 2 && die[2] > 2)
          instantW = true;
    else;
      instantW = false;
    return instantW;
  }
}
4

2 回答 2

7

else后去掉分号;它应该只是别的

我猜原因是,

instantW = false;被视为单独的语句而不是 else 块的一部分。这就是为什么 instantW 总是被赋值为 false 并返回 false 的原因。

使用 {} 定义块总是更好,即使它们是单行。这是我的偏好。

正如 Greg Hewgill 建议的那样,使用单个语句instantW = die[0] > 2 && die [1] > 2 && die[2] > 2;比 if/else 更好。

于 2012-11-01T20:08:00.307 回答
3

编写布尔方法的更好方法实际上是执行类似的操作

boolean easyW(int[] die)
{
   return (die[0] > 2 && die[1] > 2 && die[2] > 2);
}

甚至更好(更通用)

boolean easyW(int[] die)
{
   for(int roll : die)
   {
       if(roll < 2)
       {
          return false;  
       }
   }
   return true;
}

但在你的情况下,你有一个;追求。固定版本:

  public static boolean easyW (int [] die)
    {
        boolean instantW;
      // show contents of die [x] for testing
      System.out.println (die[0] + "" + die[1] + "" + die[2]);
      if (die[0] > 2 && die [1] > 2 && die[2] > 2)
            instantW = true;
         else
            instantW = false;
      return instantW;
    }
于 2012-11-01T20:11:16.733 回答