【问题标题】:Java outputting arrays and JOptionPaneJava 输出数组和 JOptionPane
【发布时间】:2021-05-03 15:59:32
【问题描述】:

我正在关注有关数组的教程,并想知道如何更改它,以便showMessageDialog 结果显示消息对话框窗口中的所有名称,而不是一一显示(我知道它在 for循环,因此它会一次弹出 1 个窗口,每个名称都有)。我尝试做 names[0] + " " + names[1] .. 等等。但是如果输入的名字比我预期的多,它会如何工作?

我希望窗口显示所有输入的名称,如果没有循环获取每个元素,我不知道如何完成。

代码:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    int length;
    String input = JOptionPane.showInputDialog("Enter amount of friends you have");
    length = Integer.parseInt(input);
    String[] names = new String[length];
    
    for(int counter = 0; counter < names.length; counter++) {
        names[counter] = JOptionPane.showInputDialog("Enter friend " + (counter + 1));
    }
   
    for (int counter = 0; counter < names.length; counter++) {  // talking about this
        JOptionPane.showMessageDialog(null, "Your friends are: " + names[counter] );
    }
}

【问题讨论】:

  • 1) 为了尽快获得更好的帮助,edit 添加minimal reproducible exampleShort, Self Contained, Correct Example。名称的硬编码数据。 2) “我正在学习一个教程” 什么教程?链接它。任何混合命令行输入和 GUI 演示的教程都从根本上被破坏了。找到更好的教程。 3)我预计(并且可以确认是否存在 MRE / SSCCE)现有答案都将失败,因为默认的 JLabel 用于在 JOptionPane 中显示信息会忽略换行符。相反,我们可以在JLabel 中使用JTextArea 或HTML 格式。
  • 4) 回到第二点。我对Scanner scanner = new Scanner(System.in); 感到困惑。此扫描仪未在代码中的其他任何地方引用,应删除。
  • 然后使用GUI based tutorial。所有 GUI 组件的创建和更新都应该在 EDT 上完成(对于初学者)。

标签: java arrays swing jlabel joptionpane


【解决方案1】:

另一个巧妙的解决方案是使用 Google 的 guava 库和 Joiner 类(但它需要外部依赖 Guava 而不是纯 JRE 函数):

String allNames = com.google.common.base.Joiner.on('\n').join(names);

https://www.baeldung.com/guava-joiner-and-splitter-tutorial 上有关 Joiner 课程的更多信息

【讨论】:

  • 此答案不使用系统特定的 EOL 字符,并且在任何情况下都会失败,因为 JLabel(用作 JOptionPane 中的默认显示元素)忽略任何形式的 EOL 字符.
【解决方案2】:

几种可能的解决方案之一:

StringBuilder allNames = new StringBuilder();
names.forEach(name -> allNames.append(name).append("\n"));
JOptionPane.showMessageDialog(null, "Your friends are: " + allNames.toString() );

【讨论】:

  • 此答案不使用系统特定的 EOL 字符,并且在任何情况下都会失败,因为 JLabel(用作 JOptionPane 中的默认显示元素)忽略任何形式的 EOL 字符.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 2023-03-26
相关资源
最近更新 更多