简体   繁体   中英

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

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

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.

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

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM