2014-02-16 64 views
1

我希望程序在用戶輸入一個小於零的值時立即結束,但此程序不斷詢問所有三個值然後退出。直到用戶輸入完所有值後,循環纔會輸入負數。

例如,如果我輸入-3,2,1,程序不進入-3第一高度後顯示錯誤,而不是需要所有三個值然後顯示「無效高度」消息。

如何讓程序顯示無效高度的錯誤信息,一旦用戶進入負值?

//Program Asking user to input three different heights 
HeightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower")); 

HeightTwo = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of Second 
Tower")); 

HeightThree = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of Third    Tower")); 

If (centimeterHeightOne < 0 || centimeterHeightTwo < 0 || centimeterThree < 0) 
{ 
    JOptionPane.showMessageDialog(null, "Invalid height"; 
} 
else 
{ 
    conditions... 
} 

回答

4

迴路不會在進入負數結束,直到用戶完成輸入 所有值。

因爲這是你在做什麼。如果你想之後的一個負值終止,把if你問每個輸入以後:

heightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower")); 
if(heightOne < 0) { 
    displayError(); 
    //return; ? 
} 
heightTwo = ... 
if(heightTwo < 0) { 
    displayError(); 
} 
... 

請按照Java Naming Conventions,改變HeightOneheightOne

+0

我明白,但問題是我不想記下錯誤消息三次。我想知道是否有任何爲什麼要把所有條件放在一起。 – user3315642

+0

@ user3315642您不必打印三次。當你顯示錯誤時,你可以做任何你想做的事情。 – Maroun

+0

有什麼辦法可以通過try/catch異常處理來做到嗎? – user3315642

0

您需要包括每個值後的檢查,像

heightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower")); 
if (heightOne < 0) { 
    JOptionPane.showMessageDialog(null, "Invalid height"); 
    return; 
} 

return聲明中止當前的方法,並返回,如果當前的方法是main,程序停止。如果您不在main方法中,但仍想強制退出該程序,則可以通過調用System.exit()來完成此操作。

+0

謝謝你。 – user3315642

相關問題