在 java 中访问 while 循环内的值?

accessing the value inside a while loop in java?

ResultSet rs2 = statement.executeQuery();
while (rs2.next()) {
    String f = rs2.getString(1);
    System.out.println(f);
   }
int a = Integer.parseInt(f);

我需要在此循环外获取字符串 f 的值并将其转换为整数。但它说 'cannot find symbol'。我如何在这个 while 循环中访问 f 的值?

如果在循环之前声明 f,则可以从循环外部访问它:

ResultSet rs2 = statement.executeQuery();
String f = null;
while (rs2.next()) {
    f = rs2.getString(1);
    System.out.println(f);
}
int a = Integer.parseInt(f);

然而,这没有什么意义,因为在循环之后 f 将包含对分配给它的最终字符串的引用,并且所有先前的字符串都将被忽略。

在循环中将 String 解析为 int 然后对其进行处理(将其添加到某个 Collection、处理它等...)会更有意义:

ResultSet rs2 = statement.executeQuery();
while (rs2.next()) {
    String f = rs2.getString(1);
    System.out.println(f);
    int a = Integer.parseInt(f);
}

只需在循环之前定义它 - 在作用域(例如循环)内创建的变量仅在该作用域内有效。

String f = null;
ResultSet rs2 = statement.executeQuery();
while (rs2.next()) {
    f = rs2.getString(1);
    System.out.println(f);
   }
int a = Integer.parseInt(f);

需要在循环外声明。

ResultSet rs2 = statement.executeQuery();
String f = new String();
while (rs2.next()) {
    f = rs2.getString(1);
    System.out.println(f);
   }
int a = Integer.parseInt(f);

基本上问题是 "Integer.parseInt(f);" 不知道 f 存在,因为 f 在循环内。

由于 "int a = Integer.parseInt(f);" 在循环之外,它无法访问循环内的内容。

在循环外设置 f。 f 当前在循环中是本地的,因此一旦 while 循环结束,它就超出了范围。在进入 while 循环之前将其定义为一个新的 String。

http://www.java-made-easy.com/variable-scope.html

要在循环外访问值——您需要在循环外定义值。 喜欢

ResultSet rs2 = statement.executeQuery();
String f = null;
while (rs2.next()) {
    f = rs2.getString(1);
    System.out.println(f);
   }
int a = Integer.parseInt(f);

但请注意,您会从此循环中收到最新的字符串值(因为在所有迭代中您都将替换此变量)。

变量 f 是它所在的块的局部变量。 您需要在块外声明它。

String f = "";
while (rs2.next()) {
    f = rs2.getString(1);

要将其转换为整数,只需使用 Integer.parseInt(f);