【问题标题】:Mastermind game if statement problems主谋游戏if语句问题
【发布时间】:2015-08-13 14:34:47
【问题描述】:

我正在努力做到这一点,所以当我的两个或多个 if 语句起作用时,它们不会都打印,而是只会说两个在正确的位置或更多它更有效。我不确定我是否应该做更多的 if 语句,如果我应该使用另一个语句或 forloop。

               //If Statements
                if (Gameboard[0] == Secret_code[0]) {
                    System.out.println ("You have one in the correct spot");
    } 
                if (Gameboard[1] == Secret_code[1]) {
                    System.out.println ("You have one in the correct spot");
    }
                if (Gameboard[2] == Secret_code[2]) {
                    System.out.println ("You have one in the correct spot");
    }
                if (Gameboard[3] == Secret_code[3]) {
                    System.out.println ("You have one in the correct spot");
    }

}
}

【问题讨论】:

  • 至少,对于某些i,您的代码似乎可以简化为if (Gameboard[i] == Secret_code[i]) { System.out.println ("You have one in the correct spot"); },例如在for 循环内。
  • 我建议先计算点击次数,然后根据该计数计算输出。

标签: java if-statement bluej


【解决方案1】:

您可以遍历Gameboard[x] == Secret_code[x] 检查并在最后打印总数。

编辑:本着促进学习的精神删除了代码。

【讨论】:

    【解决方案2】:

    解决方案“用文字”

    不要只是检查每个位置的代码是否正确然后立即打印,而是考虑创建一个变量来计算挂钩正确的次数。然后不要打印任何东西,直到你知道这个变量的值已经考虑了Secret_code 的所有元素(一个好方法(“正确”方法))这样做是循环通过@987654322 @array 并在每次代码正确时使用您的新变量进行计数。

    最后,使用保存有多少正确信息的变量将消息打印给用户。

    我不会包含示例代码,因此您可以确保自己实现和理解它:-)

    【讨论】:

      【解决方案3】:

      你可以创建一个复合条件

      if(cond1 || cond2 ||.....){print};
      

      Java 的本质是一旦遇到第一个 true 条件,就会停止进一步的评估并执行 print 语句。这只是众多解决方案之一。但是如果你的数组索引很大,我不推荐我的解决方案,因为复合条件最多只能是 3 或 4,恕我直言。

      【讨论】:

        【解决方案4】:
        if (Gameboard[0] == Secret_code[0]) {
                        System.out.println ("You have one in the correct spot");
        } 
        if (Gameboard[1] == Secret_code[1]) {
                        System.out.println ("You have one in the correct spot");
        }
        if (Gameboard[2] == Secret_code[2]) {
                        System.out.println ("You have one in the correct spot");
        }
        if (Gameboard[3] == Secret_code[3]) {
                        System.out.println ("You have one in the correct spot");
        }
        

        应该改成类似于

        private static final String[] numbers = {zero, one, two, three, four};
        
        int correctCount = 0;
        for(int i = 0; i < /*4*/ GameBoard.length; i++) {
             if(Gameboard[i] == Secret_code[i]) {
                 currentCount++;
             }
        }
        System.out.println("You have " + numbers[currentCount] + " in the correct spot.");
        

        【讨论】:

          猜你喜欢
          • 2020-06-16
          • 1970-01-01
          • 2023-02-05
          • 1970-01-01
          • 2010-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多