2013-10-04 106 views
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."); 

爲什麼它總是顯示你失去即使我的輸入是一個必須贏得的數字?條件陳述不工作Java

+0

什麼條件貢獻一場勝利? – root

+0

這是Java和**不** ** JAVA。 –

回答

6

你忘了{}對於else那就是爲什麼Lose語句總是執行。

  • 這就是爲什麼在else塊中唯一的語句是 lblRand1.setText(Integer.toString(randomNum1));
  • 之後,程序將進入正常執行lblOutput.setText("YOU LOSE.");
  • 因此,即使你的if條件true和標籤設置與You WinlblOutput.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."); 
} 
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."); 
0

你忘了其他的塊。

除此之外,您還可以使用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."); 
}