如何修复错误“线程“主”中的异常java.util.IllegalFormatConversionException:d!= java.lang.String”

时间:2019-09-04 04:57:33

标签: java

我是Java的新手,正在尝试创建一个包含所提供输入项目的数量和价格的表。

打包new.learnprogramming;

import java.text.NumberFormat;

public class Main {

public static void main(String[] args) {

NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
String apples = "Apples";
int appleQuantity = 8;
int applePrice = 400;
String oranges = "Oranges";
int orangeQuantity = 10;
int orangePrice = 150;

String column1Heading = "Fruits";
String column2Heading = "Quantity";
String column3Heading = "Price";

System.out.printf("%10s %10s %5s%n", column1Heading, column2Heading, column3Heading);
System.out.printf("%10s %8d %11d cents%n", apples, appleQuantity , currencyFormat.format(applePrice));
System.out.printf("%11s %8d %10d cents%n", oranges, orangeQuantity, currencyFormat.format(orangePrice));


}
}

我试图将输出显示为:

水果数量价格 苹果8 $ 400.00美分 橘子10 $ 150.00美分

但是,输出结果为:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4426)
at java.base/java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2938)
at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2892)
at java.base/java.util.Formatter.format(Formatter.java:2673)
at java.base/java.io.PrintStream.format(PrintStream.java:1053)
at java.base/java.io.PrintStream.printf(PrintStream.java:949)
at com.company.Main.main(Main.java:22)

3 个答案:

答案 0 :(得分:0)

NumberFormat.format(long)返回一个String(并且String的格式为%s,就像您的第一列一样)。喜欢,

System.out.printf("%10s %8d %11s cents%n", apples, 
        appleQuantity, currencyFormat.format(applePrice));
System.out.printf("%11s %8d %10s cents%n", oranges, 
        orangeQuantity, currencyFormat.format(orangePrice));

答案 1 :(得分:0)

仅修复格式说明符。 %d是十进制。

        System.out.printf("%10s %10s %5s%n", column1Heading, column2Heading, column3Heading);
        System.out.printf("%10s %8d %11s cents%n", apples, appleQuantity , currencyFormat.format(applePrice));
        System.out.printf("%11s %8d %10s cents%n", oranges, orangeQuantity, currencyFormat.format(orangePrice));

答案 2 :(得分:0)

NumberFormat.format()see this)返回String,而不是int / long / double /或类似的东西。您正在使用格式,因为您正在使用%d,但是您应该使用%s,以便正确使用String