为什么我不能在 java 中将变量作为格式字符串传递给 System.out.printf (...)? [英] Why can't I pass a variable as format string to System.out.printf (...) in java?

查看:44
本文介绍了为什么我不能在 java 中将变量作为格式字符串传递给 System.out.printf (...)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Java 中将字符串对象传递给 System.out.printf(...),但我一直收到此错误 "java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0" 这实际上对我来说没有多大意义.

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

输出如下:

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

谢谢

推荐答案

是的,这是允许的,但如果 n 为 0,它将不起作用.是否有发生这种情况的可能性(从错误消息中看起来是这样)?

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

它会打印 n is: 0 吗?

例如

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

这篇关于为什么我不能在 java 中将变量作为格式字符串传递给 System.out.printf (...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆