java.util.IllegalFormatConversionException:f!= java.lang.String错误

时间:2016-02-08 20:52:40

标签: java swing joptionpane

import javax.swing.JOptionPane;

public class Minutes {

    public static void main(String[] args) {
        double  BasePlanCost = 20;
        final double BaseCostPerMinute=0.15;

        double MinutesUsed = Double.parseDouble(JOptionPane.showInputDialog("Please enter the amount of minutes Used: "));
        double CostForMinutes = BaseCostPerMinute * MinutesUsed;
        double GrandTotal = BasePlanCost + CostForMinutes;
        JOptionPane.showMessageDialog(null, String.format("$%.2f","**IST Wireless Receipt**","\n","Base Plan Cost:" +BasePlanCost,"/n","Cost For Minutes Used: "+ CostForMinutes,"/n","Grand Total :" +GrandTotal));

    }

}

此程序输入用户输入的分钟数,并通过添加CostForMinutes和BasePlanCost计算总计。 CostForMinutes是通过乘以用户输入的分钟数和BaseCostPerMinute来计算的。 out是两位小数输出的所有数字,并作为收据输出。

当我编译程序时,它允许我输入分钟数但代码崩溃并给我这个错误

exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String

任何人都可以帮助我吗?

编辑这是我想要输出的样子   http://i.stack.imgur.com/CubfC.png

2 个答案:

答案 0 :(得分:6)

你有

String.format("$%.2f","**IST Wireless Receipt**",

这意味着您希望使用%.2f格式化第二个参数,该参数是一个浮点格式,不起作用。

您需要将格式重新组织为第一个格式以及要在其后格式化的值。

String.format("**IST Wireless Receipt**%n" +
              "Base Plan Cost: $%.2f%n" +
              "Cost For Minutes Used: $%.2f%n" +
              "Grand Total: $%.2f%n",
              BasePlanCost, CostForMinutes, GrandTotal)

答案 1 :(得分:0)

尝试将您的信息整理为:

String message = String.format(
            "**IST Wireless Receipt** \n" + 
            " Base Plan Cost:$ %.2f \n" +
            " Cost For Minutes Used: $ %.2f \n" +
            " Grand Total : $ %.2f", BasePlanCost, CostForMinutes, GrandTotal);

    JOptionPane.showMessageDialog(null, message);

我建议你阅读java语言的代码约定

http://www.oracle.com/technetwork/java/codeconventions-135099.html