Sajith
Sajith

Reputation: 113

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);

I need to get value of string f outside this loop and convert it to integer. But it says 'cannot find symbol'. How can i access the value of f inside this while loop?

Upvotes: 1

Views: 7506

Answers (6)

Jack
Jack

Reputation: 6620

The variable f is local to the block that it is located in. You need to declare it outside the block.

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

To covert it to integer just use Integer.parseInt(f);

Upvotes: 0

Atomfinger
Atomfinger

Reputation: 714

You need to declare it outside the loop.

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

Basically the problem is that "Integer.parseInt(f);" does not know that f exists since f is inside the loop.

Since "int a = Integer.parseInt(f);" is outside the loop it cannot access the contents within the loop.

Upvotes: 1

Eran
Eran

Reputation: 393846

You can access it from outside the loop if you declare f before the loop :

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

However, it makes little sense, since after the loop f will contain a reference to the final String that was assigned to it, and all the previous Strings will be ignored.

It would make more sense to parse the String to int inside the loop and then do something with it (add it to some Collection, process it, etc...) :

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

Upvotes: 2

iMysak
iMysak

Reputation: 2228

To have access to a value OUTSIDE the loop — you need define value outside the loop. like

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

But be aware that you receive the LATEST string value from this loop (cause on all iteration you will replace this variable).

Upvotes: 1

MrB
MrB

Reputation: 818

Set f up outside the loop. f is currently local to the loop so its out of scope once the while loop is ended. Define it as a new String before you enter the while loop.

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

Upvotes: 0

Martin
Martin

Reputation: 7714

Just define it before your loop - variable created inside a scope (such as a loop) are only valid inside this scope.

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

Upvotes: 1

Related Questions