Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm getting an error with System.out.printf()

I am getting a run time error and I cannot figure out why. Although I have figured out that it is happening because of the following line of code.

System.out.printf("\n\nThe total bill for your group is $%.2f before taxes. The HST (13%) will be $%.2f.", totalBill, amountOfTax);

totalBill and amountOfTax are both float type variables.

I am fairly new to programming and have hardly any experience with using printf. I have a very similar line of code earlier in the program that does essentially the same thing and it runs fine.

The error that I am getting is as follows:

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ')'
    at java.util.Formatter.checkText(Formatter.java:2579)
    at java.util.Formatter.parse(Formatter.java:2555)
    at java.util.Formatter.format(Formatter.java:2501)
    at java.io.PrintStream.format(PrintStream.java:970)
    at java.io.PrintStream.printf(PrintStream.java:871)
    at RestaurantOrder.main(RestaurantOrder.java:220)

Thanks for any help, I appreciate it!

ps. I should note that I am using Eclipse Luna (4.4.0)

like image 334
Brandon Turner Avatar asked Feb 28 '26 10:02

Brandon Turner


2 Answers

You need to escape % sign in format string. "13%" becomes "13%%":

System.out.printf("\n\nThe total bill for your group is $%.2f before taxes. " + 
    "The HST (13%%) will be $%.2f.", totalBill, amountOfTax);
like image 153
LeffeBrune Avatar answered Mar 02 '26 22:03

LeffeBrune


The percent sign for (13%) is being interpreted as a placeholder. It's looking for characters after the % for details about how to format a variable there, and ) isn't valid.

You meant to have a literal % in the output, not interpreted as a placeholder. It must escaped with another % sign. Try:

System.out.printf(
  "\n\nThe total bill for your group is $%.2f before taxes. The HST (13%%) will be $%.2f.",
  totalBill, amountOfTax);

See the Formatter javadocs for details:

The format specifiers which do not correspond to arguments have the following syntax:

%[flags][width]conversion

And

'%' percent The result is a literal '%' ('\u0025')

like image 23
rgettman Avatar answered Mar 02 '26 22:03

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!