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?
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!
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.