0
int number;
  int randomNum1= (int)(Math.random() * 12 + 1);
 int randomNum2= (int)(Math.random() * 12 + 1);
    try{
        number = Integer.parseInt(this.txtInput.getText());
    }
    catch (Exception e){
        JOptionPane.showMessageDialog(this, "Please input a integer.", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;
        }                
    if (number > randomNum1 && number < randomNum2 ||  number > randomNum2 && number  < randomNum1){
    lblRand1.setText(Integer.toString(randomNum1));
    lblRand2.setText(Integer.toString(randomNum2));
    lblOutput.setText("YOU WIN.");
    }else
    lblRand1.setText(Integer.toString(randomNum1));
    lblRand2.setText(Integer.toString(randomNum2));
    lblOutput.setText("YOU LOSE.");

为什么它总是显示你输了,即使我输入的是一个必须赢的数字?

4

3 回答 3

6

你忘{}else这就是为什么Lose总是执行语句。

  • 这就是为什么else块中唯一的语句是 lblRand1.setText(Integer.toString(randomNum1));
  • 之后,程序将正常流动执行lblOutput.setText("YOU LOSE.");
  • 因此,即使您的if条件是true并且标签设置为You Win,lblOutput.setTest("You Lost")也会作为正常程序执行的结果执行,因为它不在else块中

改变

else
lblRand1.setText(Integer.toString(randomNum1));
lblRand2.setText(Integer.toString(randomNum2));
lblOutput.setText("YOU LOSE.");

else{

lblRand1.setText(Integer.toString(randomNum1));
    lblRand2.setText(Integer.toString(randomNum2));
    lblOutput.setText("YOU LOSE.");
}
于 2013-10-04T10:03:48.327 回答
1

永远不要使用没有花括号的语句(请参阅您的else!)

if ([...]){
  ...
}else
lblRand1.setText(Integer.toString(randomNum1));
lblRand2.setText(Integer.toString(randomNum2));
lblOutput.setText("YOU LOSE.");

相当于

if ([...]){
  ...
} else {
  lblRand1.setText(Integer.toString(randomNum1));
}
lblRand2.setText(Integer.toString(randomNum2));
lblOutput.setText("YOU LOSE.");
于 2013-10-04T10:05:41.110 回答
0

你忘记了 else 的块。

此外,您可以使用Math.maxMath.min简化您的条件

lblRand1.setText(Integer.toString(randomNum1));
lblRand2.setText(Integer.toString(randomNum2));
if (number > Math.min(randomNum1, randomNum2) 
    && number < Math.max(randomNum1, randomNum2)){
    lblOutput.setText("YOU WIN.");
} else {
    lblOutput.setText("YOU LOSE.");
}
于 2013-10-04T10:05:49.103 回答