2013-06-12 38 views
0

我有一個嵌套在for循環內的while循環內創建的字符串數組。這與從Derby中的字符串列創建數組有關,但爲了簡單起見,我將省略一些東西。訪問字符串兩個循環外的數組

我不提供完整代碼的原因是因爲問題非常具體。我對我的數據庫,結果集,語句或查詢沒有任何問題。它只是訪問兩個循環之外的數組。

//in the class, 
private int rowCount; //Count of the rows in my column of strings 
public String stringArray[]; 


//in the method I am using 
public void myMethod() { 
    rowCount = 4; //In my code it actually counts it, lets say its four though. 
    stringArray = new stringArray[rowCount]; //set 
    for (int i = 0; i < rowCount; i++) { 
     while (rs.next()/*rs is simply a result set of a statement executeQuery to select the correct table*/) 
     { 
      stringArray[i] = rs.getString(2); //2 is the column number in the table 
     } 
    } 
//Need to access stringArray here. When I try to print out values, it always prints out as null. 
} 

謝謝!

+2

那麼,什麼是問題? – gma

+0

你可以訪問循環外的數組。你的問題是在其他地方,而不是讀取值 –

+0

嘗試在你的循環內打印字符串**(或者使用調試器來查看實際放入字符串的內容)。我敢打賭,你的價值觀也是空的 –

回答

1

你的嵌套循環有問題。對於每一行(i的每個值/外循環的每次執行),您遍歷整個結果集並覆蓋很多次(覆蓋範圍爲stringArray[i])。

當你到達第二行(即i是1或更高)時,rs.next()已經是false,因爲你在外循環的第一次迭代中遍歷了整個rs。

也許你只是需要一個單一的調用來替換你的內環while(rs.next())rs.next()

+0

我實際上通過改變循環來解決它: for(int i = 0; i

0

也許在您的實際代碼,你說:

rowCount = 4; //In my code it actually counts it, lets say its four though. 

你被執行的行數做類似的事情:

for(rowCount = 0; rs.next(); rowCount++) { } 

如果您正在做類似的事情,那麼您基本上已經讀過國家中的所有行當你嘗試重新處理行時,rs.next()方法只是返回false,因爲它已經讀取了所有的行。

當然,我只是猜測......