Java 如何在单个消息框中显示循环的所有迭代?
一切都正常工作,没有逻辑或语法错误,但是,我需要在最后的代码显示一个单一的消息框,它像一个表一样一次显示所有迭代,而不是让x个消息框弹出结果。我不知道该怎么做,我的教科书中只有类似的例子没有使用消息框Java 如何在单个消息框中显示循环的所有迭代?,java,loops,joptionpane,Java,Loops,Joptionpane,一切都正常工作,没有逻辑或语法错误,但是,我需要在最后的代码显示一个单一的消息框,它像一个表一样一次显示所有迭代,而不是让x个消息框弹出结果。我不知道该怎么做,我的教科书中只有类似的例子没有使用消息框 import java.text.DecimalFormat; import javax.swing.JOptionPane; public class PenniesForPay { public static void main(String[] args) {
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);
}
}
导入java.text.DecimalFormat;
导入javax.swing.JOptionPane;
公费
{
公共静态void main(字符串[]args)
{
国际日;
int最大天数;
双薪=0.01;
double totalPay;//累加器
字符串输入;
//用于格式化输出的十进制格式对象
DecimalFormat dollar=新的DecimalFormat(“0.00”);
//获取天数
input=JOptionPane.showInputDialog(“您工作了多少天?”);
maxDays=Integer.parseInt(输入);
//有效天数
而(最大天数<1)
{
input=JOptionPane.showInputDialog(“天数必须至少为一天”);
天=整数.parseInt(输入);
}
//将累加器设置为0
工资总额=0.0;
//展示台
for(days=1;days在for循环外部使用您的JOptionPane.showMessageDialog
。使用StringBuffer或StringBuilder附加消息并立即显示。您可以使用a累积所有消息,然后在循环完成后显示一次:
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());
StringBuilder sb=新建StringBuilder();
for(days=1;days)在for循环之前创建一个StringBuffer
,在for循环内部将当前放入JOptionPane
的内容附加到它,同时从for循环中删除JOptionPane
代码并将其置于for循环之后。。