开发者

Java: Literal percent sign in printf statement

开发者 https://www.devze.com 2022-12-10 20:42 出处:网络
I\'m trying to add a开发者_开发技巧n actual percent sign into a printf statement in Java and I\'m getting the error:

I'm trying to add a开发者_开发技巧n 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?


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.


Escaped percent sign is double percent (%%):

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


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


Check below Code ---

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

精彩评论

暂无评论...
验证码 换一张
取 消