java.util.IllegalFormatConversionException: f != java.lang.String Error

折月煮酒 提交于 2019-12-01 21:25:05

问题


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

    }

}

This program inputs the amount of minutes the user enters and calculates the grand total by adding the CostForMinutes and BasePlanCost. CostForMinutes is calculated by multiplying the minutes the user enters and the BaseCostPerMinute. The out is all the numbers outputted by two decimal places and outputted as a receipt.

When I compile the program it lets me input the amount of minutes but the code collapses and gives me this error

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

can anyone help me out?

EDIT this is what I want the output to look like http://i.stack.imgur.com/CubfC.png


回答1:


You have

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

This means you want to format the second argument which is a String using %.2f which is a float format which won't work.

You need to re-organize your format to be first and the values you want to format after it.

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



回答2:


Try to organize your message as:

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

I recommended you to read the code conventions of the java language

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



来源:https://stackoverflow.com/questions/35279083/java-util-illegalformatconversionexception-f-java-lang-string-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!