In this Example we are going to understand the String Format of strings and the errors
Error Message :
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%2$s'
at java.base/java.util.Formatter.format(Formatter.java:2678)
at java.base/java.util.Formatter.format(Formatter.java:2609)
at java.base/java.lang.String.format(String.java:2988)
at com.si.Strings.StrinFormat.main(StrinFormat.java:9)
Error Description :
package com.si.Strings;
public class StrinFormat {
public static void main(String[] args) {
String str = "Surya Infoware";
String str2 = "very good";
String str1 = String.format("My company name is : %1$s %1$s and %2$s", str);
System.out.println(str1);
}
}
In the above program we get an error in the red background line.
In the String format we are giving some wrong number of input formats to print the strings.
The number of different parameters in the String format and the values should be same type.
Due to this we are getting MissingFormatArgumentException.
Solution:
In this program %1$s is type of str and %2$s is str2 String. We should give all the types of parameters and the values accordingly to avoid this type of exceptions in the String Formats.
package com.si.Strings;
public class StrinFormat {
public static void main(String[] args) {
String str = "Surya Infoware";
String str2 = "very good";
String str1 = String.format("My company name is : %1$s %1$s and %2$s", str,str2);
System.out.println(str1);
}
}
Output:
My company name is : Surya Infoware Surya Infoware and very good
Post a comment
Please share your valuable feedback and share this article in social media.