0

Here's the printf statement that's giving me the error:

System.out.printf("%-*s%*s", dateTimeWidth, dateTime, locationWidth, location);

I want dateTime to be printed left-aligned with width dateTimeWidth and location to be printed right-aligned with width locationWidth. Both locationWidth and dateTimeWidth are passed in as ints.

Here's the error I'm getting:

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '-'
    at java.util.Formatter.checkText(Formatter.java:2503)
    at java.util.Formatter.parse(Formatter.java:2485)
    at java.util.Formatter.format(Formatter.java:2414)
    at java.io.PrintStream.format(PrintStream.java:920)
    at java.io.PrintStream.printf(PrintStream.java:821)
    at TicketMaker.drawTicket(TicketMaker.java:43)
    at TicketMaker.main(TicketMaker.java:12)

I believe something is wrong with my syntax, but I'm not sure what I'm doing wrong.

Info on printf with asterisks here

Community
  • 1
  • 1
  • What do you think `*` in `%-*s` represents? Also could you share some link where we could read about it? – Pshemo Oct 03 '14 at 21:59
  • I believe you want numbers instead of *'s. http://web.cerritos.edu/jwilson/SitePages/java_language_resources/Java_printf_method_quick_reference.pdf – SnakeDoc Oct 03 '14 at 22:05
  • In researching, I may have answered my own question. I believe the * only works in C. – Logan Kirkland Oct 03 '14 at 22:07

1 Answers1

2

Declare an extra variable before using printf:

String format = "%-" + dateTimeWidth + "s%" + locationWidth + "s";
System.out.printf(format, dateTime, location);
maszter
  • 3,680
  • 6
  • 37
  • 53