在 JOptionPane.showMessageDialog 中设置小数点的格式



我的代码是一个不断发展的过程,最终的游戏是使用JOptionPane实现我以前的迭代的UI。我使用 String.format("文本在这里 %.2f",变量(成功地将输出格式化为小数点后 2 位,但是当我尝试使用 JOptionPane 将此方法带到我的代码迭代中时,它使程序崩溃。

这是我的代码

import javax.swing.JOptionPane;
public class Ass1d2
{
public static void main(String [] args)
{
final int N = 7;
String taxPayerName;
int taxPayerIncome = 0;
double maxTax = 0.0;
String maxTaxName = "";
JOptionPane.showMessageDialog(null, "Welcome to use Tax Computation System");
for(int i = 0; i < N; i++)
{
taxPayerName = (String)JOptionPane.showInputDialog(null, "Enter tax payers name");
taxPayerIncome =  Integer.parseInt(JOptionPane.showInputDialog(null, "Enter income for the tax payer"));
double tax = computeTax(taxPayerIncome);
if (taxPayerIncome > maxTax){
maxTax = tax;
maxTaxName = taxPayerName;
}
JOptionPane.showMessageDialog(null, "The tax that " + taxPayerName + " owes is $" + tax));
}
JOptionPane.showMessageDialog(null, "The maximum tax is $" + maxTax) + " paid by " + maxTaxName);
}
private static double computeTax(int taxPayerIncome)
{
double tax = 0.0;
if (taxPayerIncome < 18200)
tax = 0;
else if (taxPayerIncome < 37000)
tax = (taxPayerIncome - 18200) * 0.19;
else if (taxPayerIncome < 87000)
tax = 3572 + (taxPayerIncome - 37000) * 0.325;
else if (taxPayerIncome < 180000)
tax = 19822 + (taxPayerIncome - 87000) * 0.37;
else
tax = 54232 + (taxPayerIncome - 180000) * 0.47;
return tax;
}
}

如何格式化两个 showMessageDialog 以生成两个小数点浮点结果?在过去的一个小时里,我一直在搜索指南,但它只是没有点击。非常令人沮丧的是,这是最后的障碍。谢谢。

好吧,我一定在我的其他尝试中做了一个错字,因为我现在让它工作了。尴尬。附加了带有工作浮点结果的更新代码以供将来参考。

import javax.swing.JOptionPane;
public class Ass1d2
{
public static void main(String [] args)
{
final int N = 3;
String taxPayerName;
int taxPayerIncome = 0;
double maxTax = 0.0;
String maxTaxName = "";
JOptionPane.showMessageDialog(null, "Welcome to use Tax Computation System");
for(int i = 0; i < N; i++)
{
taxPayerName = (String)JOptionPane.showInputDialog(null, "Enter tax payers name");
taxPayerIncome =  Integer.parseInt(JOptionPane.showInputDialog(null, "Enter income for the tax payer"));
double tax = computeTax(taxPayerIncome);
if (taxPayerIncome > maxTax){
maxTax = tax;
maxTaxName = taxPayerName;
}
JOptionPane.showMessageDialog(null, "The tax that " + taxPayerName + " owes is $" + String.format("%.2f", tax));
}
JOptionPane.showMessageDialog(null, "The maximum tax is $" + String.format("%.2f", maxTax) + " paid by " + maxTaxName);
}
private static double computeTax(int taxPayerIncome)
{
double tax = 0.0;
if (taxPayerIncome < 18200)
tax = 0;
else if (taxPayerIncome < 37000)
tax = (taxPayerIncome - 18200) * 0.19;
else if (taxPayerIncome < 87000)
tax = 3572 + (taxPayerIncome - 37000) * 0.325;
else if (taxPayerIncome < 180000)
tax = 19822 + (taxPayerIncome - 87000) * 0.37;
else
tax = 54232 + (taxPayerIncome - 180000) * 0.47;
return tax;
}
}

最新更新