user1949186
user1949186

Reputation: 83

How to access the string variable outside the for loop in java?

for the following code which I worked on.Now the problem is how do I access the variable string outside the for loop?Thank you.

for (String[] string: arr) {
    if(string.length == 1)
    { 
        System.out.println(string[0]);
        continue;
    }
    for (int i = 1; i < string.length; i++)  {
        System.out.println(string[0] + " " + string[i]);
    }
}

Upvotes: 2

Views: 6283

Answers (5)

user1985027
user1985027

Reputation:

The following solution provides you the arraylist of all the Strings that are printed. This provides an arraylist created with the string array logic to use it beond the for loop.

Use the finalList to print all the Strings even after the for loop.

ArrayList<String> finalList = new ArrayList<String>();

    for (String[] string: arr) {

        if(string.length == 1)
        { 
            System.out.println(string[0]);
            finalList.add(string[0]);
            continue;
        }
        for (int i = 1; i < string.length; i++)  {
            System.out.println(string[0] + " " + string[i]);                
            finalList.add(string[0] + " " + string[i]);
        }   
    }

    for(String output: finalList){
        System.out.println(output);
    }

Hope this helps.

Upvotes: 2

user1760178
user1760178

Reputation: 6657

Try this.

String[] outerString  = {}; 

    for (String[] string: arr) {
        outerString = string;
        if(string.length == 1)
        { 
            System.out.println(string[0]);
            continue;
        }
        for (int i = 1; i < string.length; i++)  {
            System.out.println(string[0] + " " + string[i]);
        }   
    }

    if(outerString.length > 0){
        System.out.println(outerString[0]);
    }

Do remember that only the last item in the Collection iteration will be printed in the outer string.

Upvotes: 0

Peter Gluck
Peter Gluck

Reputation: 8236

Your string variable is locally scoped and only exists within the loop. You need to define an external String[] variable first, then make an assignment to that variable within the loop:

String[] outsideString;

for (String[] string: arr) {
  ...
  outsideString = string;
  ...
}

// This line works
System.out.println(outsideString[0]);

Upvotes: 3

Aurand
Aurand

Reputation: 5537

You can't. If you need to access something from the loop outside of said loop, create a String or Collection variable outside of the loop and assign/add to it from inside the loop.

Upvotes: 0

DotNetRussell
DotNetRussell

Reputation: 9857

You can't given this code. In the enhanced for loop that you have at the top you can only use that variable local to that for loop

Upvotes: 0

Related Questions