简体   繁体   English

条件语句不起作用Java

[英]conditional statement not working Java

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.");

why does it always display you lose even my input is a number that must win? 为什么即使我输入的数字必须赢,它也总是显示您输了?

You forgot {} for else thats why Lose statement is always executed. 你忘了{}对于else这就是为什么Lose始终执行的语句。

  • Thats why the only statement in else block is lblRand1.setText(Integer.toString(randomNum1)); 这就是为什么else块中唯一的语句是lblRand1.setText(Integer.toString(randomNum1));
  • After that, program will flow normally to execute lblOutput.setText("YOU LOSE."); 之后,程序将正常运行以执行lblOutput.setText("YOU LOSE.");
  • Hence, even if your if condition is true and label is set with You Win , lblOutput.setTest("You Lost") is executed as result of normal program execution as it is not in else block 因此,即使您的if条件为true且使用You Win设置了标签, lblOutput.setTest("You Lost")由于正常程序执行而执行了lblOutput.setTest("You Lost") ,因为它不在else块中

Change 更改

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

to

else{

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

Never use statements without curly braces (see your else !) 切勿使用不带花括号的语句(请参见else !)

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

is equivalent to 相当于

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

You forgot the block for the else. 您忘记了其他的障碍。

Besides you can use Math.max and Math.min to simplify your condition 此外,您可以使用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.");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM