Java: Literal percent sign in printf statement

JavaPrintfEscaping

Java Problem Overview


I'm trying to add an actual percent sign into a printf statement in Java and I'm getting the error:

lab1.java:166: illegal escape character
                System.out.printf("%s\t%s\t%1.2f\%\t%1.2f\%\n",ID,pattern,support,confidence);
                                                 ^
lab1.java:166: illegal escape character
                System.out.printf("%s\t%s\t%1.2f\%\t%1.2f\%\n",ID,pattern,support,confidence);
                                                          ^
2 errors

I can't figure out how to put an actual percent sign into my printf? I thought using % to escape it would work, but it isn't.

Any ideas?

Java Solutions


Solution 1 - Java

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

Solution 2 - Java

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

Solution 3 - Java

You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.

Solution 4 - Java

Check below Code ---

public class Printer {
   public static void main(String[] args) {
      System.out.printf("2 out of 10 is %d%%", 20);
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDom M.View Question on Stackoverflow
Solution 1 - JavasoulmergeView Answer on Stackoverflow
Solution 2 - JavacletusView Answer on Stackoverflow
Solution 3 - JavaHarkamwaljeet SinghView Answer on Stackoverflow
Solution 4 - JavaRaj K PachauriView Answer on Stackoverflow