2015-02-12 156 views
0

編輯:用戶輸入一個正數,代碼從該數字變爲1.例如用戶輸入一個8,所以它變爲8,7 ,6,5,4,3,2,1.「while」和「do while」驗證for「for」循環

邏輯部分正在工作。我在驗證用戶輸入負數時遇到問題。

這是我有,但它不工作。

String stringSeries = ""; 

    int userInput = userInput = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive number to evaluate")); 

    for (int i = 1; userInput >= i; userInput--) 
    { 
     while (userInput <= 0) 
     { 
      userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a valid number")); 
     } 

     stringSeries +=userInput+ ", "; 
    } 
    System.out.println(stringSeries); 

當我輸入一個負數時,程序會說「構建成功」,而它應該再次要求輸入一個正數。

另外,我怎樣才能做到這一點呢?

+1

我們應該如何知道你在嘗試做什麼? – The111 2015-02-12 05:01:58

+0

請提供您想要做的事情。只是寫它的不工作不會讓我們明白你想要執行什麼 – 2015-02-12 05:03:13

+0

好吧,用戶輸入一個正數,代碼從該數字變爲1.例如,用戶輸入一個8,所以它走8,7,6 ,5,4,3,2,1 – fredy21 2015-02-12 05:03:47

回答

2

如果我正確理解你的意圖,你正在嘗試讀入一個整數,確認它大於0,然後以降序將這個數字中的所有數字打印到1。

如果是這種情況,問題在於你的while循環的位置。 for循環的條件是userInput> = i。您爲i指定了1的值。鑑於此,如果userInput < = 0(您對while循環的條件),則for循環內的代碼將永遠不會執行(因爲userInput> = i,或等價地userInput> = 1永遠不會)。修正將是你之前移動while語句for循環,使其:

String stringSeries = ""; 

int userInput = userInput = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive number to evaluate")); 

while (userInput <= 0) 
{ 
    userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a valid number")); 
} 

for (int i = 1; userInput >= i; userInput--) 
{ 
    stringSeries +=userInput+ ", "; 
} 
System.out.println(stringSeries); 

的結構和成語幾點意見:在你的作業第二userInput是不必要的。通常在for循環中,我(您的迭代變量)是要更改的值。這樣做的一個更地道的辦法是:

String stringSeries = ""; 

int userInput = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive number to evaluate")); 

while (userInput <= 0) 
{ 
    userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a valid number")); 
} 

for (int i = userInput; i >= 1; i--) 
{ 
    stringSeries += i+ ", "; 
} 
System.out.println(stringSeries); 

如果你想使用while循環一做,代碼將是:

String stringSeries = ""; 

int userInput;  
do { 
    userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a valid number")); 
} while(userInput <= 0); 

for (int i = userInput; i >= 1; i--) 
{ 
    stringSeries += i+ ", "; 
} 
System.out.println(stringSeries); 
+0

我說的很多! – rayryeng 2015-02-12 05:10:09

+0

謝謝!我真笨。只需要在外面放一會兒。 :/ – fredy21 2015-02-12 05:14:37

0

你可以這樣做。

int userInput = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive number to evaluate"));   
do{ 
    System.out.print(userInput + ","); 
    }while(--userInput > 0); 
+0

否。如果用戶輸入負數,則會終止程序。 OP希望繼續詢問一個數字,直到插入一個正數。 – rayryeng 2015-02-12 14:19:53