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!
while loop? What do you say?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);
String foo="something";set a default value.I think the error you are getting is that you dint declare foo you only initialize it .