Cmau
Cmau

Reputation: 51

How to show all iterations of a loop, within a single message box?

Everything is working properly, no logic or syntax errors, however, I need the code at the end to display a single message box that shows all iterations at once like a table, as opposed to having x amount of message boxes pop up with results. I'm not sure how to go about it, the only similar examples in my textbook don't use message boxes.

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

    }
}

Upvotes: 3

Views: 1719

Answers (2)

Mureinik
Mureinik

Reputation: 311438

You can use a StringBuilder to accumulate all the messages, and then display them, once, after the loop is done:

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

Upvotes: 3

Aninda Bhattacharyya
Aninda Bhattacharyya

Reputation: 1251

Use your JOptionPane.showMessageDialog outside the for loop. Use StringBuffer or StringBuilder to append your messages and show at once.

Upvotes: 1

Related Questions