2014-02-07 51 views
0

我試圖創建一條錯誤消息,該方法允許用戶輸入一年中每個月的降雨量。我試圖阻止數據存儲在數組中。我正在使用do-while循環,但似乎無法弄清楚如何檢查輸入是否小於零。謝謝你們的幫助,歡呼!如果數組中輸入的數據小於零,輸入驗證

public static double[] getRainFall() 
    { 
     double[] rainfallMonths = new double[12]; 
     double[] rainfall = new double[12]; 

     do 
     { 
      for(int x = 0; x < rainfallMonths.length; x++) 
      { 
        System.out.print("What is the rainfall for month #" + (x + 1) + ": "); 
       rainfallMonths[x] = keyboard.nextDouble(); 
       rainfall[x] = rainfallMonths[x]; 

       if(rainfallMonths < 0) 
       { 
        System.out.println("Input is Invalid"); 
       } 
      } 
     }while(rainfallMonths < 0); 


     for(int count = 0; count < rainfallMonths.length; count++) 
     { 
      System.out.println("Rainfall Month #" + (count + 1) + ": " + rainfall[count]); 
     } 

     return rainfall; 
    } 
+2

'如果(rainfallMonths [X] <0)'...但你會想改變周圍的這點你循環... – MadProgrammer

+0

'rainfallMonths'只是一個參考。你可能想檢查一下'rainFallMonths [index]' –

+0

你想在rainMonths <0的時候結束循環,而且你已經弄錯了你的代碼。參見@MadProgrammer的上面評論。 – Jaykishan

回答

2

你的邏輯是有點過,更不要說你想一個數組進行比較的int ......

首先,邏輯......

do 
    for x = 0 to rainfallMonths.length -1 do 
     ... get input... 
while value < 0 

問題在於,您已將輸入分配給for-next循環中的數組的所有元素,但是您試圖驗證在for-next之外輸入的值,該值可能永遠不會返回有效結果。 ..太遲了.. 。

相反,要扭轉邏輯...

for x = 0 to rainfallMonths.length -1 do 
    do 
     value = get input from user 
    while value < 0 
    rainfallMonths[x] = value 

接下來,rainfallMonths是一個數組的引用,這實際上不是要被檢查反對什麼,你需要檢查對一個它的值或元素,例如...

while (rainfallMonths[x] < 0); 

,如果沒有那是有道理的......

public static double[] getRainFall() 
{ 
    double[] rainfallMonths = new double[12]; 
    double[] rainfall = new double[12]; 

    for(int x = 0; x < rainfallMonths.length; x++) 
    { 
     double input = 0; 
     System.out.print("What is the rainfall for month #" + (x + 1) + ": "); 
     do { 
      rainfallMonths[x] = keyboard.nextDouble(); 
      rainfall[x] = rainfallMonths[x]; 
      if(input < 0) 
      { 
       System.out.println("Input is Invalid"); 
      } 
     } while (rainfallMonths[x] < 0);  
    } 


    for(int count = 0; count < rainfallMonths.length; count++) 
    { 
     System.out.println("Rainfall Month #" + (count + 1) + ": " + rainfall[count]); 
    } 

    return rainfall; 
} 

你可能想進修上Arrays這應有助於;)

+0

是的,我意識到我應該做的 - 而在for循環內。我在城市大學學習java課程,陣列開始變得有點棘手。謝謝您的幫助! –

+0

查看最後的鏈接數組教程 - 很高興它幫助... – MadProgrammer

0
double temp = -1; 
for(int x = 0; x < rainfallMonths.length; x++) 
     { 
      System.out.print("What is the rainfall for month #" + (x + 1) + ": "); 
      temp = keyboard.nextDouble(); 
      if(temp < 0) 
      { 
       System.out.println("Input is Invalid"); 
       x--; //if you want the user to maybe try to repeat this month again? 
      } 
      else 
      { 
       rainfallMonths[x] = keyboard.nextDouble(); 
       rainfall[x] = rainfallMonths[x]; 
      } 
     } 
+0

我從來沒有見過這樣做過。謝謝您的幫助! –