Reputation: 117
I've this variable:
String foo;
for(String links: Result){
String myVariable="\n"+foo;
}
System.out.println(foo); //loop is giving error here..
How to use foo
variable outside for loop
in Java?
Upvotes: 1
Views: 2718
Reputation: 3831
you just need to do
String foo=null; //or any default value you want your string to contain
for(String links: Result){
String myVariable="\n"+foo;
}
System.out.println(foo);
your error is, you have declared a variable but not initialized it,
you can have a look at this link to understand why this error was caused.
Hope this helps!
Good luck!
Upvotes: 2
Reputation: 6670
Here, you could almost eliminate the for loop, entirely, and see the issue with the code in your post (as the for
loop is not actually doing anything to String foo
. So, as another user suggested, although you have declared foo
, you have not done anything with the variable to give it a value.
So, your code is essentially:
String foo;
System.out.println(foo);
Were your for
loop to modify foo
, then you would see a result:
String foo;
for(String links: Result){
foo = foo + "a value added each time the loop iterates";
}
System.out.println(foo);
Upvotes: 0