我有一种方法,在计算费用并向其加费后,将总价格打印为双倍。
public static String printWarehouseCharge(Warehouse w[])
{
String wc = "";
for(int i=0; i < 4; i++)
{
// method that calculates charge and returns a double
double warehouseCharge = w[i].calculateWarehouseCharge();
//here the calculateTransportFee method adds a fee and returns the total to be printed
wc = wc+String.format("$%,.2f", w[i].calculateTransportFee(warehouseCharge) +"\n");
}
return wc;
}
不幸的是,我一直收到格式错误:IllegalFormatConversionException
。
任何人都可以帮助我吗?
答案 0 :(得分:2)
问题是因为您尝试在下面的行中添加一个带字符串的数字。
w[i].calculateTransportFee(warehouseCharge) +"\n"
从w [i]返回的内容.calculateTransportFee(warehouseCharge)是一个float或double的数字,你可以将它添加到\n
。
这对你有用......
wc = wc+String.format("$%,.2f", w[i].calculateTransportFee(warehouseCharge)) +"\n";
答案 1 :(得分:1)
问题是在+"\n"
double
附加String.format
,IllegalFormatConversionException
wc = wc+String.format("$%,.2f",
w[i].calculateTransportFee(warehouseCharge)); // Remove "\n"
答案 2 :(得分:1)
当格式说明符对应的参数属于不兼容类型时,您可能会收到IllegalFormatConversionException。在您的代码中,您指定方法'format'应该是浮点数。您提供的不是'warehouseCharge',而是字符串'warehouseCharge +“\ n”'。添加字符串和数字时,结果始终为字符串。
答案 3 :(得分:1)
问题是String.format
方法的争论。您的第二个参数预计为double/float
,但由于 concantenation
String
wc = wc+String.format("$%,.2f", w[i].calculateTransportFee(warehouseCharge) +"\n");
^^^^^^^^^
Here is the error because the 2nd argument gets converted into String
试试这个
wc = wc+String.format("$%,.2f", w[i].calculateTransportFee(warehouseCharge));
wc+= "\n";