简体   繁体   中英

Java printf error when using asterisks

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

Declare an extra variable before using printf:

String format = "%-" + dateTimeWidth + "s%" + locationWidth + "s";
System.out.printf(format, dateTime, location);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM