Java:printf 语句中的文字百分号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1708444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Literal percent sign in printf statement
提问by Domenic
I'm trying to add an actual percent sign into a printf statement in Java and I'm getting the error:
我正在尝试将实际百分号添加到 Java 中的 printf 语句中,但出现错误:
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.
我不知道如何将实际百分号放入我的 printf 中?我认为使用 \% 来逃避它会起作用,但事实并非如此。
Any ideas?
有任何想法吗?
采纳答案by soulmerge
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 syntaxcan be accessed in java docs. This particular information is in the section Conversions
of the first link.
该完整语法可以访问Java文档。此特定信息位于第Conversions
一个链接的部分中。
The reason the compiler is generating an error is that only a limited amount of charactersmay follow a backslash. %
is not a valid character.
编译器产生错误的原因是只有有限数量的字符可以跟在反斜杠后面。%
不是有效字符。
回答by cletus
Escaped percent sign is double percent (%%):
转义百分号是双百分号 (%%):
System.out.printf("2 out of 10 is %d%%", 20);
回答by Harkamwaljeet Singh
You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.
您可以使用 Apache Commons Logging 实用程序中的 StringEscapeUtils 或使用每个字符的代码手动转义。