2017-09-06 53 views
-3

編輯:如果我問這個錯誤,我很抱歉。我的預期結果是最終以循環運行兩次。我只希望得到: System.out.println(inventory [0] [1]); System.out.println(inventory [1] [1]);For Loop似乎要跑兩次

我有我認爲是一個簡單的循環從數據庫拉,並將每個結果添加到一個字符串數組。

while(rs3.next()) { 
    for(int c = 0; c < iCount; c++) { 
     inventory[c][0] = rs3.getString(10);      
     inventory[c][1] = rs3.getString(9);      

     System.out.println(inventory[c][1]); //#&(*& WHY IS THIS HAPPENING TWICE 

     inventory[c][3] = Integer.toString(rs3.getInt(3));  
     inventory[c][6] = rs3.getString(6);      
     inventory[c][10] = Integer.toString(rs3.getInt(12));  
     inventory[c][12] = Integer.toString(rs3.getInt(13));  
     inventory[c][31] = Integer.toString(rs3.getInt(14));  
     inventory[c][32] = Integer.toString(rs3.getInt(15));  
     inventory[c][34] = Integer.toString(rs3.getInt(16));  
     inventory[c][52] = rs3.getString(4);      
     inventory[c][53] = Integer.toString(rs3.getInt(5)); 
     inventory[c][18] = Integer.toString(rs3.getInt(7));  
     inventory[c][29] = Integer.toString(rs3.getInt(8));  
     inventory[c][78] = Integer.toString(rs3.getInt(1));  
    } 
} 

int iCount在本例中設置爲2,我使用System.out.println()進行檢查。

問題是,它會記錄每個值兩次(每個循環,因此在此示例中共有4次)這會拋出使用此數據的其他方法。

我添加了println(inventory [c] [1]);向我自己確認它確實正在爲for循環的每個循環執行兩次這個操作。

+2

我不知道如果我的理解,但如果'iCount'是'2',那麼你的'for'循環會爲每次迭代執行的兩次'while'循環。這意味着,例如,您的'System.out.println()'將執行兩次。 – dave

+0

這就像你問,「爲什麼這個循環,從i = 0到i <2,循環兩次? –

+0

設置iCount = 1,並檢查你是否得到預期的結果如果答案是肯定刪除問題。其他的詳細信息 – Steephen

回答

0

我想你想:

int c = 0; 
while(rs3.next()) { 
    inventory[c][0] = rs3.getString(10);      
    inventory[c][1] = rs3.getString(9);      

    System.out.println(inventory[c][1]); 

    // ... rest omitted for brevity 

    c++; 
} 
+0

謝謝!這就是它,現在我明白,雖然本身是一個循環,但我正在學習嬰兒步驟,學習G。 – Shlim