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

I tried 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 doesn't really make much 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

      

thank

+3


source to share


1 answer


Yes, it is allowed, but it will not work if n is 0. Is there any chance of this happening (looks like 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 print n is: 0?

eg.

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");
  }      
}

      

+10


source







All Articles