Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pass a variable as format string to System.out.printf (...) in java?

Tags:

java

printf

I was trying to pass a string object to System.out.printf(...) in Java, but I kept getting this error "java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0" which actually doesn't make a lot of sense to me.

String format = "%" + (3 * n) + "s"; // n is an int defined somewhere above, could be 0
System.out.printf(format, "My string");

Does anyone know if this is allowed?

Edit for more details:

int n = 0;
String fm = "%" + (3 * level) + "s";
String realFm = "%0s";
System.out.println("fm = " + fm);
System.out.println("realfm = " + realFm);
System.out.println("equals? " + (fm.equals(realFm)));
System.out.printf(fm, " ");

Here's the output:

fm = %0s
realfm = %0s
equals? true
java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0

Thanks

like image 555
user113454 Avatar asked Dec 09 '22 01:12

user113454


1 Answers

Yes it's allowed, but it won't work if n is 0. Is there a chance of this happening (looks like it from the error message)?

what if you add a line to your code to debug it:

// line added below for debugging. To remove later:
System.out.println("n is: " + n); 

String format = "%" + (3 * n) + "s"; // n is an int defined somewhere above
System.out.printf(format, "My string");

Does it ever print n is: 0?

e.g.,

public static void main(String[] args) {

  // try the for loop with n = 0 vs. n = 1
  for (int n = 1; n <= 10; n++) {
     // line added below for debugging. To remove later:
     System.out.println("\nn is: " + n); 

     String format = "%" + (3 * n) + "s"; 
     System.out.printf(format, "My string");
  }      
}
like image 151
Hovercraft Full Of Eels Avatar answered May 20 '23 13:05

Hovercraft Full Of Eels