[英]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
始终执行的语句。
else
block is lblRand1.setText(Integer.toString(randomNum1));
else
块中唯一的语句是lblRand1.setText(Integer.toString(randomNum1));
lblOutput.setText("YOU LOSE.");
lblOutput.setText("YOU LOSE.");
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.max
和Math.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.