简体   繁体   English

如何在Java中的for循环外访问字符串变量?

[英]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循环外访问变量字符串?谢谢。

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. 您的string变量在本地范围内,仅存在于循环中。 You need to define an external String[] variable first, then make an assignment to that variable within the loop: 您需要先定义一个外部String[]变量,然后在循环中对该变量进行赋值:

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 . 这提供了一个使用字符串数组逻辑创建的arraylist,以便在for loop使用它。

Use the finalList to print all the Strings even after the for loop . 即使在for loop之后,也for loop使用finalList打印所有字符串。

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 在顶部的增强型for循环中,只能使用for循环本地的变量

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. 如果需要从所述循环外部的循环访问某些内容,请在循环外部创建String或Collection变量,然后从循环内部为其分配/添加变量。

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. 请记住,只有Collection迭代中的最后一项将被打印在外部字符串中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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