如何在java中的for循环之外的for循环中存储for循环字符串

时间:2015-08-10 11:24:46

标签: java

我想要的是我需要访问存储在for循环中的字符串,以便在for循环之外访问。因为我需要它用于另一个操作。我尝试在循环外创建另一个字符串并分配相同的字符串变量,但它不可能。我能以任何方式实现它吗?

for (int index = 0; index < nodeList.getLength(); index++) {
     System.out.println(nodeList.item(index).getTextContent());
      String excelpath1 = nodeList.item(index).getTextContent();

    }

现在我想在for循环之外访问excelpath1。请告诉我,我可以通过它来实现它。

4 个答案:

答案 0 :(得分:0)

由于可变可见性的范围,你做这件事的方式是不可能的,因为它只能在环路中可见并存在

你可以在循环之前声明String,但我不知道循环多个条目并将值保存在单个String中会很有用。

String excelpath1;
for (int index = 0; index < nodeList.getLength(); index++) {
     System.out.println(nodeList.item(index).getTextContent());
     excelpath1 = nodeList.item(index).getTextContent();
}

答案 1 :(得分:0)

在循环之外声明它。

String excelpath1 = null;
for (int index = 0; index < nodeList.getLength(); index++) {
     System.out.println(nodeList.item(index).getTextContent());
      excelpath1 = nodeList.item(index).getTextContent();
    }
System.out.println("excelpath1 is " + excelpath1);

答案 2 :(得分:0)

在for循环之外声明String,如下所示

String excelpath1 = null;

并在内部初始化for循环。您也可以在外部使用此值进行循环。

每次存储最新值。这意味着在存在for循环之前存储的值。

答案 3 :(得分:0)

您应该使用StringBuilder代替String,并避免String内的for loop对象创建。

        StringBuilder sb=new StringBuilder();
        for (int index = 0; index < nodeList.getLength(); index++) {
             sb.append(nodeList.item(index).getTextContent());
        }
        System.out.println(sb);