Mastermind游戏如果声明问题

时间:2015-05-30 21:06:04

标签: java if-statement bluej

我试图这样做,当我的两个或多个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");
    }

}
}

4 个答案:

答案 0 :(得分:1)

您可以循环检查Gameboard[x] == Secret_code[x]个检查并在结尾打印总数。

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

答案 1 :(得分:0)

解决方案"用词"

不要只检查每个点中的代码是否正确然后立即打印,而是考虑创建一个变量,该变量将计算挂钩正确的次数。然后不要打印任何东西,直到你知道这个变量的值已经考虑了Secret_code的所有元素(一种好方法("右边"方式))来做这将循环遍历Secret_Code数组,并在每次代码正确时使用新变量进行计数。

最后,使用变量将消息打印给用户,该变量包含有关正确数量的信息。

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

答案 2 :(得分:0)

You could create a compound condition

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

The nature of Java is that once the first true condition is encountered, further evaluation stops and the print statement is executed. This is just one of many solutions. But if your array index is huge, I don't recommend my solution since a compound condition should only be about 3 or 4 at most, IMHO.

答案 3 :(得分:0)

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.");
相关问题