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.
}

谢谢!

4

2 回答 2

1

你的嵌套循环有问题。对于每一行(i 的每个值 / 外部循环的每次执行),您都会遍历整个结果集并stringArray[i]多次覆盖(我没有改变)。

当您到达第二行时(即 i 为 1 或更高), rs.next() 已经为假,因为您在外循环的第一次迭代中遍历了整个 rs 。

也许您只需要while(rs.next())通过一次调用来替换您的内部循环rs.next()

于 2013-06-12T16:04:49.643 回答
0

也许在您的实际代码中,您说:

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

您正在通过执行以下操作来执行行数:

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

如果您正在做类似的事情,那么您基本上已经在计数阶段读取了所有行,并且当您稍后尝试重新处理行时, rs.next() 方法只会返回 false ,因为它已经读取了所有行。

当然,我只是猜测...

于 2013-06-12T21:46:38.143 回答