不知道为什么我的代码给我一个“非法格式转换异常”错误?

时间:2015-01-29 19:59:49

标签: 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)

4 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:0)

您应该决定是否要使用似乎更适合您的printf()println()

System.out.println(3 + "\tTelevision\t" + TV_price + "\t" + tax * TV_price + " " + TV_price);

使用printf(),您首先完整地放置格式字符串,然后是所有值,如下所示:

System.out.printf("%d number %s string\n", 3, "hi");

答案 2 :(得分:0)

由于这一行,你得到了这个例外:

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

由于TVs + "\tTelevision\t%f"+正在尝试进行算术运算。

您应格式化输出,然后提供值。

实施例: System.out.printf("%d %s", TVs, "\tTelevision\");

答案 3 :(得分:0)

我并不是特别熟悉java,但我所知道的几乎所有“打印格式”函数都遵循格式字符串的模式,然后是所有参数。

喜欢这样

printf("This is a string %d %d %s %f", arg1, arg2, arg3, arg4);

您似乎要做的是同时执行格式字符串和正常连接。