java-如何在单个消息框中显示循环的所有迭代?

一切正常,没有逻辑或语法错误,但是,我需要在代码末尾显示一个消息框,该消息框像表一样一次显示所有迭代,而不是弹出带有结果数量的消息框.我不确定该怎么做,教科书中唯一类似的例子都没有使用消息框.

import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class PenniesForPay
{
    public static void main(String[] args)
    {
      int days;     
      int maxDays; 
      double pay = 0.01;       
      double totalPay;     //accumulator
      String input;

      //Decimal Format Object to format output
      DecimalFormat dollar = new DecimalFormat("#,##0.00");

      //Get number of days
      input = JOptionPane.showInputDialog("How many days did you work?");

      maxDays = Integer.parseInt(input);
      //Validate days
      while (maxDays < 1)
      {
         input = JOptionPane.showInputDialog("The number of days must be at least one");

         days = Integer.parseInt(input);
      }

      //Set accumulator to 0
      totalPay = 0.0;

      //Display Table
      for (days = 1; days <= maxDays; days++)
      {
         pay *= 2;
         totalPay += pay; //add pay to totalPay

        // NEEDS TO SHOW ALL ITERATIONS IN SINGLE MESSAGE BOX 
        JOptionPane.showMessageDialog(null,"Day   " + "    Pay" + "\n----------------\n" +
                                          days + "         $" + pay + "\n----------------\n" +
                                           "Total Pay For Period: $" + dollar.format(totalPay));
      }
      //terminate program   
      System.exit(0);    

    }
}

解决方法:

您可以使用StringBuilder累积所有消息,然后在循环完成后将它们显示一次:

StringBuilder sb = new StringBuilder();
for (days = 1; days <= maxDays; days++) {
     pay *= 2;
     totalPay += pay; //add pay to totalPay

    sb.append("Day       Pay\n----------------\n")
      .append(days)
      .append("         $")
      .append(pay)
      .append("\n----------------\n")
      .append("Total Pay For Period: $")
      .append(dollar.format(totalPay));
}
JOptionPane.showMessageDialog(sb.toString());
上一篇:如何将Java中的2D数组打印到Swing / JOptionPane中的窗口


下一篇:java-更改JOptionPane中的图标