java - 为什么我会遇到异常(exception)?

标签 java exception runtime-error printf decimalformat

请帮忙。当扫描仪的提示显示到控制台后,我收到此错误:

Exception in thread "main" java.util.IllegalFormatPrecisionException: 2
at java.util.Formatter$FormatSpecifier.checkInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.<init>(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at Project6.main(Project6.java:56)

问题是出在 printf 上吗?我检查了格式,看起来是正确的。
程序如下:

import javax.swing.JOptionPane; // allows for message dialog

import java.util.Scanner; // allows for Scanner object to be used

import java.text.DecimalFormat; // allows for formatting numbers


public class Project6 { 


public static void main (String[] args)  {      

    final double LUXURYRATE = .2; // rate of luxury tax
    final double STATERATE = .1; // rate of state tax
    final double LABORRATE = .05; // rate of labor cost

    double diamondCost; // cost of diamond, value comes from the Scanner
    double settingCost; // cost of setting, value comes from the Scanner
    int numOrdered; // quantity ordered, value comes from the Scanner
    double baseCost ; //sum of the values in the variables for diamond and  setting
    double totalCost; // total cost including tax
    double laborCost; // cost of labor
    double stateTax; // cost of state tax
    double luxuryTax; // cost of luxury tax
    double finalAmountDue; // total cost times quantity ordered

    DecimalFormat formatter = new DecimalFormat("$#,##0.00"); // money format

        Scanner input = new Scanner (System.in); // creates Scanner object  
        System.out.print("Enter diamond cost:"); // prompts user
        diamondCost = input.nextDouble(); // converts input to double

        System.out.print("Enter setting cost:"); // prompts user
        settingCost = input.nextDouble(); // converts input to double

        System.out.print("Enter quantity:"); // prompts user
        numOrdered = input.nextInt(); // converts input to integer          

        baseCost = diamondCost + settingCost; // calculates the cost before multiplication

        laborCost = calcExtraCost(LABORRATE , baseCost); // calls method calcExtraCost for calculation
        stateTax = calcExtraCost(STATERATE, baseCost); // calls method calcExtraCost for calculation
        luxuryTax = calcExtraCost(LUXURYRATE, baseCost); // calls method calcExtraCost for calculation

        totalCost = baseCost + laborCost + stateTax + luxuryTax; // total cost including tax and labor costs
        finalAmountDue = totalCost * numOrdered; // calculates total    

    System.out.printf("Diamond Cost: $%,.2d \n", diamondCost); // displays bill to console
    System.out.printf("Setting Cost: $%,.2f \n", settingCost);
    System.out.printf("State Tax @ 10%: $%,.2f \n", stateTax);
    System.out.printf("Luxury Tax @ 20%: $%,.2f \n", luxuryTax);
    System.out.printf("Labor Charge @ $5% %,.2f \n", laborCost);
    System.out.printf("Total Price: $%,.2f \n" , totalCost);
    System.out.printf("Number Ordered: $%,.2d \n", numOrdered);
    System.out.printf("Amount Due: $%,.2f \n", finalAmountDue);


    JOptionPane.showMessageDialog(null, "Diamond Cost: " + formatter.format(diamondCost) + "\n" + 
                                        "Setting Cost: " + formatter.format(settingCost) + "\n" +
                                        "State Tax @ 10%: " + formatter.format(stateTax) + "\n" +
                                        "Luxury Tax @ 20%: " + formatter.format(luxuryTax) + "\n" + 
                                        "Labor Charge @ 5% " + formatter.format(laborCost) + "\n" +
                                        "Total Price: " + formatter.format(totalCost) + "\n" +
                                        "Number Ordered: " + formatter.format(numOrdered) + "\n" +
                                        "Amount Due: " + formatter.format(finalAmountDue) ); // displays bill in message dialog     


} // end method main 


public static double calcExtraCost (double RATE, double bcost) {

    double cost = RATE * bcost; // calculates extra cost

    return cost; // returns value of extra cost



     } // end method calcExtraCost


} // end class Project6

最佳答案

答:因为您的格式说明符与 printf 方法中使用的输入参数不匹配。

使用 %f 而不是 %d 作为 double 值的格式说明符

System.out.printf("Diamond Cost: $%,.2f \n", diamondCost); 
                                      ^

此外 % 需要额外的 % 来转义该字符

System.out.printf("State Tax @ 10%%: $%,.2f \n", stateTax);

最后,删除不必要的点字符

System.out.printf("Number Ordered: $%,.2d \n", numOrdered);
                                      ^

阅读:Formatter javadoc

关于java - 为什么我会遇到异常(exception)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19775242/

相关文章:

java.lang.OutOfMemoryError : bitmap size exceeds VM budget & java. io.FileNotFoundException

java - 为什么 session bean 方法在抛出 RuntimeException 时抛出 EjbTransactionRolledbackException

java - 在 Spring Data JPA 中的单个事务中保存、删除和更新

exception - Topology出现Exception则跳过记录

c# - 内存不足异常

visual-studio - Visual Studio 2017 错误 : dep6200: bootstrapping failed

java - 有没有关于使用 spring security 实现 2-legged oauth 的引用?

java - 无效 key 异常 : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

Java 控制台在 AMD 64 位平台上无法运行 : Can't load IA 32-bit . dll

.net - 类型为 'System.NullReferenceException' 的未处理异常 - 具有结构