java - 不确定为什么我的代码给出 "Illegal Format Conversion Exception"错误?

标签 java

我很确定错误是由最后一行引起的..据我所知,我对使用“%d”变量感到不满意。但这不是整数的有效输入吗?

import java.util.Scanner;

public class total_cost {
    public static void main(String[] args) {

        int TVs;
        int VCRs;
        int controller;
        int CD;
        int recorder;
        double TV_price;
        double VCR_price;
        double controller_price;
        double CD_price;
        double recorder_price;
        double tax;
        {
            TV_price = 400.00;
            VCR_price = 220.00;
            controller_price = 35.20;
            CD_price = 300.00;
            recorder_price = 150.00;
            tax = .0825;

            Scanner in = new Scanner(System.in);
            {
                System.out.printf("How many TV's were sold? ");
                TVs = in.nextInt();

                System.out.printf("How many VCR's were sold? ");
                VCRs = in.nextInt();

                System.out.printf("How many remote controller's were sold? ");
                controller = in.nextInt();

                System.out.printf("How many CD players were sold? ");
                CD = in.nextInt();

                System.out.printf("How many Tape Recorder's were sold? ");
                recorder = in.nextInt();

                System.out.printf("QTY\tDESCRIPTION\tUNIT PRICE\tTOTAL PRICE\n");
                System.out.printf("%d", TVs + "\tTelevision\t%f", TV_price
                        + "\t" + tax * TV_price + "%f", TV_price);
            }
        }
    }
}

错误消息:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4011)
    at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2725)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2677)
    at java.util.Formatter.format(Formatter.java:2449)
    at java.util.Formatter.format(Formatter.java:2383)
    at java.lang.String.format(String.java:2781)
    at total_cost.main(total_cost.java:37)

最佳答案

您传递的是字符串,而不是整数。应该是这样的:

System.out.printf("%d\tTelevision\t%.2f\t%.2f,%.2f", TVs, TV_price,tax * TV_price, TV_price);

PS:我可以自由地将价格格式化为小数点后两位。

关于java - 不确定为什么我的代码给出 "Illegal Format Conversion Exception"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223514/

相关文章:

java - spring-Unnamed bean 定义既不指定 'class' 也不指定 'parent' 也不指定 'factory-bean' - 无法生成 bean 名称

java - 使用 MaryTTS 嵌入时如何使用其他声音?

java - 从 View 检索数据的查询不起作用

java - ionic 3 显示错误 src/android/com/tkyaji/cordova/DecryptResource.java not found

java - Java 和 C 之间的压缩兼容性

java - AutoBean、数组/列表属性和 JSNI

Java 枚举定义

java - Hibernate事务处理问题

java - 存储应用程序设置而不是使用首选项

java - MVC 中的哪个组件可以引用有什么限制吗?