【问题标题】:String.format() takes an array as a single argumentString.format() 将数组作为单个参数
【发布时间】:2021-02-17 17:56:48
【问题描述】:

为什么这样可以正常工作?:

String f = "Mi name is %s %s.";
System.out.println(String.format(f, "John", "Connor"));

这不?:

String f = "Mi name is %s %s.";
System.out.println(String.format(f, (Object)new String[]{"John","Connor"}));

如果方法 String.format 采用可变参数对象?

它可以编译,但是当我执行此操作时,String.format() 将 vararg 对象作为单个唯一参数(数组本身的 toString() 值),因此它会引发 MissingFormatArgumentException,因为它无法与第二个字符串说明符 (%s)。

我怎样才能让它工作? 提前致谢,任何帮助将不胜感激。

【问题讨论】:

  • 不确定,但您可以在不将字符串数组转换为对象的情况下进行检查吗?

标签: java string string-formatting


【解决方案1】:

使用这个:(我会推荐这种方式)

String f = "Mi name is %s %s.";
System.out.println(String.format(f, (Object[])new String[]{"John","Connor"}));

String f = "Mi name is %s %s.";
System.out.println(String.format(f, new String[]{"John","Connor"}));

但是如果你使用这种方式,你会得到以下警告:

String[] 类型的参数应显式转换为Object[],以便从String 类型调用varargs 方法format(String, Object...)。也可以将其转换为 Object 以进行 varargs 调用。

【讨论】:

    【解决方案2】:

    问题是在转换为Object 之后,编译器不知道您正在传递一个数组。尝试将第二个参数转换为 (Object[]) 而不是 (Object)

    System.out.println(String.format(f, (Object[])new String[]{"John","Connor"}));
    

    或者根本不使用演员表:

    System.out.println(String.format(f, new String[]{"John","Connor"}));
    

    (有关更多信息,请参阅this answer。)

    【讨论】:

    • 谢谢,它适用于 Object[] cast。强制转换是避免编译警告所必需的。再次感谢。
    • @Dragurne - 为避免编译器警告和强制转换,您可以使用 new Object[]{"John","Connor"}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    相关资源
    最近更新 更多