Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use string format %s and '%' in the same line?

Here is simple string format and it works.

String format = "Your name is %s";
String text = String.format(format, "Harry");

System.out.print(text);//print "Your name is Harry"

But when I use "%" in the same line

String format = "Your name is %s, 100%point";
String name = String.format(format, "Harry");

System.out.print(name);// I want to print "Your name is Harry, 100%point"

I want to print "Your name is Harry, 100%point",

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but it come into runtime error

 java.util.UnknownFormatConversionException: Conversion = 'p'
        at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2781)
        at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2811)
        at java.util.Formatter$FormatSpecifierParser.<init>(Formatter.java:2624)
        at java.util.Formatter.parse(Formatter.java:2557)
        at java.util.Formatter.format(Formatter.java:2504)
        at java.util.Formatter.format(Formatter.java:2458)
        at java.lang.String.format(String.java:2842)

How to solve it.
Any help will be appreciate.

>Solution :

You need to escape % with another %, i.e. %%.

String format = "Your name is %s, 100%%point";
String name = String.format(format, "Harry");

System.out.print(name); // I want to print "Your name is Harry, 100%point"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading