gpt4 book ai didi

java - 我想在 JOptionPane 中显示 for 循环的输出

转载 作者:行者123 更新时间:2023-12-05 09:07:22 25 4
gpt4 key购买 nike

我有一个 ArrayList,我想遍历 ArrayList 并将数组列表中的项目打印到 JOptionPane.showInput 对话框。但是我如何在 JOptionPane 中使用循环结构?下面的代码显示了多个 JOptionPane 窗口,很明显它会显示,因为它在一个循环中。任何人都可以修改它以仅显示一个 JOptionPane 窗口并在一个窗口中输出所有消息。

public void getItemList(){
for (int i=0; i<this.cartItems.size(); i++){
JOptionPane.showInputDialog((i+1) + "." +
this.cartItems.get(i).getName(););
}

}

最佳答案

您可以将 cartItems 的所有元素附加到 StringBuilder 中,并仅使用 StringBuilder 显示 JOptionPane循环终止后一次。

import java.util.List;

import javax.swing.JOptionPane;

public class Main {
List<String> cartItems = List.of("Tomato", "Potato", "Onion", "Cabbage");

public static void main(String[] args) {
// Test
new Main().getItemList();
}

public void getItemList() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.cartItems.size(); i++) {
sb.append((i + 1) + "." + this.cartItems.get(i)).append(System.lineSeparator());
}
JOptionPane.showInputDialog(sb);
}
}

enter image description here

关于java - 我想在 JOptionPane 中显示 for 循环的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64951377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com