2013-11-22 47 views
1

我剛剛在這一點上學習了基本的東西,但是我已經傾斜了我的大腦,試圖將用戶輸入帶入下面的ArrayList並驗證該輸入不是負數。我可能會想,但是如果你能幫到,請告訴我。使用ArrayList驗證UserInput不是負數

感謝

public static ArrayList<Double> readcuinput() 
{ 
    ArrayList<Double> cuinput; 
    cuinput = new ArrayList<Double>(); 
    boolean IsNegative; 

    do{ 
     IsNegative = false; 
     System.out.println("Enter value, " 
     + "Q to quit: "); 
     Scanner in = new Scanner(System.in); 
     while (in.hasNextDouble()) 
     { 
      cuinput.add(in.nextDouble()); 
      for (int i = 0; i < cuinput.size();i++) 
      { 
       if (cuinput.get(i) < 0) 
       { 
        System.err.println("Error: Must not be a Negative Value"); 
        IsNegative = true; 
       } 
      } 
     } 
     }while(IsNegative = true); 
    return cuinput; 
+0

我們可以幫你 –

+0

我的意思是,你有沒有關於特定問題這個? – yamafontes

+1

在'while'條件下將'='更改爲'=='。 – Christian

回答

0
while條件

首先改變===

第二,如果最後的輸入是,從陣列中刪除:

... 
if (cuinput.get(i) < 0) { 
    System.err.println("Error: Must not be a Negative Value"); 
    IsNegative = true; 
    cuinput.remove(i); // ADD THIS 
} 
... 
+0

謝謝你們是最好的。奇蹟般有效。在我的循環順序中是否有一個簡單的修復方法來提示用戶重新輸入一個值,如果他們得到錯誤vs必須輸入Q重新啓動。 – user3020517

0

簡體

public static ArrayList<Double> readcuinput() { 
    ArrayList<Double> cuinput= new ArrayList<Double>(); 
    Scanner in = new Scanner(System.in); 
    while (in.hasNextDouble()) { 
     double value = in.nextDouble(); 
     if (value < 0) { 
      System.err.println("Error: Must not be a Negative Value"); 
      break; 
     } 
     cuinput.add(value); 
    } 
    return cuinput; 
}