0

I have a method that prints out the total price as a double after calculating the charge and adding a fee to it.

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;
}

Unfortunately I keep getting a format error: IllegalFormatConversionException. Can anyone help me?

1
  • simply your calculateTransportFee method do not return a correct float. Commented Nov 28, 2013 at 6:56

4 Answers 4

2

The issue is because you are trying to add a number with a string in the below line. w[i].calculateTransportFee(warehouseCharge) +"\n"

what is returned from w[i].calculateTransportFee(warehouseCharge) is a number either float or double and you are addin git it to \n.

This should work for you...

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

Sign up to request clarification or add additional context in comments.

Comments

1

The problem is argument to the String.format method. Your second argument is expected to be double/float but it is actually String due to concantenation

wc = wc+String.format("$%,.2f",  w[i].calculateTransportFee(warehouseCharge) +"\n");
                                                                          ^^^^^^^^^
                                                        Here is the error because the 2nd argument gets converted into String

Try this

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

Comments

1

The problem is appending +"\n" with double at String.format which is a IllegalFormatConversionException

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

Comments

1

You might get IllegalFormatConversionException when the argument corresponding to the format specifier is of an incompatible type. In your code you specified that the method 'format' should expect floating point number. You provided not 'warehouseCharge' , but the string 'warehouseCharge + "\n"'. When adding string and a number, the result is always string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.