1

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?

6
  • where is your variable 'foo' declared? Commented Mar 6, 2015 at 16:47
  • but what is foo? where it is initialized Commented Mar 6, 2015 at 16:47
  • Don't worry about that it's declared fine! Commented Mar 6, 2015 at 16:47
  • 1
    String foo="something"; set a default value.I think the error you are getting is that you dint declare foo you only initialize it . Commented Mar 6, 2015 at 16:49
  • @singhakash: You have that backwards - foo is declared, but not initialized. Commented Mar 6, 2015 at 17:17

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

6 Comments

Okay.. Let me try this first. I'd accept your answer!
No dude.. I tried your answer.. It is getting only one Answer while declaring it.. Any possibilities by using while loop? What do you say?
if you can provide what is your expected output and what is your achieved output with your latest code, it will be easier to solve this
@Rajkumar are you still stuck?
Dude.. I'm want to get the result of that loop, but unfortunately ..I'm getting only one result. Here loop is not working.. :(
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.