2013-11-28 123 views
0

我有一种方法,在计算费用并向其中添加费用后,将总价格打印为双倍数。字符串格式错误

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

简单你的'calculateTransportFee'方法不返回正确的浮动。 – erencan

回答

1

问题在String.formatdouble附加+"\n"这是一个IllegalFormatConversionException

wc = wc+String.format("$%,.2f", 
    w[i].calculateTransportFee(warehouseCharge)); // Remove "\n" 
1

你可能会得到IllegalFormatConversionException当对应于格式说明符的参数为不兼容的类型。在你的代码中,你指定方法'format'应该是浮点数。您提供的不是'warehouseCharge',而是字符串'warehouseCharge +“\ n”'。当添加字符串和数字时,结果总是字符串。

1

问题是String.format方法的参数。你第二参数预期为double/float,但它实际上是String由于concantenation

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"; 
2

的问题是,因为你尝试添加一些用字符串在下面的行中。 w[i].calculateTransportFee(warehouseCharge) +"\n"

取之于W [I] .calculateTransportFee(warehouseCharge)返回的是一个数字,要么float或double和你的插件它GIT中\n

这应该为你工作...

wc = wc+String.format("$%,.2f", w[i].calculateTransportFee(warehouseCharge)) +"\n";