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.");
为什么它总是显示你输了,即使我的输入是一个必须赢的数字?
答案 0 :(得分:6)
您忘了{}
else
这就是为什么Lose
语句总是被执行的原因。
else
块中唯一的陈述是
lblRand1.setText(Integer.toString(randomNum1));
lblOutput.setText("YOU LOSE.");
if
条件为true
且标签设置为You Win
,lblOutput.setTest("You Lost")
也会因正常程序执行而执行,因为它不在{ {1}}阻止更改
else
到
else
lblRand1.setText(Integer.toString(randomNum1));
lblRand2.setText(Integer.toString(randomNum2));
lblOutput.setText("YOU LOSE.");
答案 1 :(得分: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.");
答案 2 :(得分:0)
你忘记了别人的阻拦。
此外,您可以使用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.");
}