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

时间:2015-10-05 18:23:18

标签: java loops joptionpane

一切正常,没有逻辑或语法错误,但是,我需要最后的代码显示一个消息框,它像表一样显示所有迭代,而不是 x 弹出结果的消息框数量。我不知道如何去做,我教科书中唯一类似的例子不使用消息框。

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);    

    }
}

2 个答案:

答案 0 :(得分:3)

您可以使用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());

答案 1 :(得分:1)

在for循环外使用JOptionPane.showMessageDialog。使用StringBuffer或StringBuilder来附加消息并立即显示。