Why are printf not working properly in Java? JAVA

2.1k Views Asked by At

I am getting this type of error in my eclipse software :

Question

Why do I get an error?

code :

    package loops;
    public class Escapey {
        public static void main(String[] args) {
            String name ="micheal";
            System.out.printf("i am %s, my friend name also %s",name);
        }
    }

Error message:

Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%s' at java.base/java.util.Formatter.format(Formatter.java:2672) at java.base/java.io.PrintStream.format(PrintStream.java:1053) at java.base/java.io.PrintStream.printf(PrintStream.java:949) at loops.Escapey.main(Escapey.java:5)

  • Ouput excepted :(
5

There are 5 best solutions below

2
On

A pretty obscure way to do this:

System.out.printf("i am %s, my friend's name also %<s", name);

I have literally never used this, but it is mentioned in the documentation of Formatter.

Another way to reference arguments by position is to use the '<' ('\u003c') flag, which causes the argument for the previous format specifier to be re-used.

0
On

By having two %s the printf is expecting two arguments

like

System.out.printf("i am %s, my friend's name also %s",name, name);
0
On

use this ...

System.out.printf("i am %s, my friend name also %s",name, name);

You are giving two specifiers. So you need to give name twice here.

4
On

One solution,

System.out.print("i am " + name + ", my friend name also " + name); // If you want to continue on same line 
System.out.println("i am " + name + ", my friend name also " + name); // If you want to continue on next line 

Since you have two %s, two arguments are expected, so either you specify two arguments.

System.out.printf("i am %s, my friend name also %s",name, name);

Or specify an index in the string. %1$s will get the first argument, in this case name.

System.out.printf("i am %1$s, my friend's name also %1$s", name);

Read more here! :)

Java printf( ) Method Quick Reference

Java Format - Java printf Value Index // explicit indexing, relative indexing

6
On

You can either specify the argument twice, or specify an index when referenced in the format string:

System.out.printf("i am %1$s, my friend's name also %1$s", name);