如何在 for 循环之外访问 [0 到 9] 中的字符串列表?

How can I access the Strings list from [0 to 9] outside for loop?

我正在尝试编写允许我访问 String msgbody 并将其放入电子邮件中的代码。然而,使用下面的代码只有最终的 String 出现在 for 循环之外。我搜索了很多次答案,对 Java.

有点陌生
    List<String> urls = new ArrayList<String>();
    String msgbody = "";
       for (int i = 0; i < urls.size(); i++) {
            //urls.get(i); unecessary
            // String msgbody0; - Used to attempt msgbody0 = url.get(i); then msgbody += msgbody0; but only prints first url
            int sum = i + 1;
            for (j = 1; j < 2 ; j++)
            {
                msgbody = urls.get(i);

                //urls.add(msgbody); not needed
                System.out.print("("+ sum +")" +"");
                System.out.println(msgbody); 
            }
            if(i==9){
                break;
            }
        } // Inside the for loop everything prints properly.

       System.out.println(msgbody); // How can i replicate it here?(Outside for loop)

编辑: 这有效: (最初-下面只重复显示第一个link:) 我从 Java 更改为 Java EE,它有效吗?我错过了什么?

    msgbody += urls.get(i);

我可以让它在没有 for 循环的情况下工作,但它很草率。

您可以将 msgbody = urls.get(i); 更改为 msgbody += urls.get(i);(否则每次迭代都会完全替换 msgbody)。另外,我更喜欢 StringBuilder, the diamond operator <> and a for-each loop。喜欢,

List<String> urls = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (String url : urls) {
    sb.append(urls.get(url));
}
System.out.println(sb);

唯一的细微变化是您要替换 msgbody 而不是连接它。

List<String> urls = new ArrayList<String>();
    String msgbody = "";
       for (int i = 0; i < urls.size(); i++) {
            //urls.get(i); unecessary
            // String msgbody0; - Used to attempt msgbody0 = url.get(i); then msgbody += msgbody0; but only prints first url
            int sum = i + 1;
            for (j = 1; j < 2 ; j++)
            {
                msgbody += urls.get(i);

                urls.add(msgbody);
                System.out.print("("+ sum +")" +"");
                System.out.println(msgbody); 
            }
            if(i==9){
                break;
            }
        } // Inside the for loop everything prints properly.

       System.out.println(msgbody);