gpt4 book ai didi

Java格式化数组(使用Formatter类)

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:36:00 27 4
gpt4 key购买 nike

我们有这样的方法:

public String getCommandString(Object...args) {
return this.code + " " + String.format(this.pattern, args);
}

其中 this.code:intthis.pattern:String

这个方法通常这样调用:

// cmd.code = 20
// cmd.pattern = "%1$s = %2$d"
String str = cmd.getCommandString("foo", 3); // -> "20 foo = 3"

和其他字符串模式(这是一个非常简单的基于文本的服务器-客户端程序)

现在,模式是否可以考虑可变数量的参数,例如

// cmd.code = 20
// cmd.pattern = ???
String s1 = cmd.getCommandString("a", "b", "c"); // -> 20 a b c
String s2 = cmd.getCommandString("Hello", "world"); // -> 20 Hello world
String s3 = cmd.getCommandString("1", "2, "3", "4", "5", "6"); // -> 20 1 2 3 4 5 6

假设每个参数都属于同一类型(字符串)?还是我必须重写该方法并手动格式化字符串?更具体地说,我正在寻找一种通用字符串模式来格式化可变数量的参数(相同类型)。我记得用 C 做过这样的事情,但这在 Java 中可行吗?

最佳答案

如果我理解正确,您要求的功能不存在。这是 Formatter 类的 javadoc 部分:

Format specifiers can reference arguments in three ways:

Explicit indexing is used when the format specifier contains an argument index. The argument index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc. An argument may be referenced more than once. For example:

formatter.format("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s", "a", "b", "c", "d") // -> "d c b a d c b a"

Relative indexing is used when the format specifier contains a '<' ('\u003c') flag which causes the argument for the previous format specifier to be re-used. If there is no previous argument, then a MissingFormatArgumentException is thrown.

formatter.format("%s %s % "a b b b" // "c" and "d" are ignored because they are not referenced

Ordinary indexing is used when the format specifier contains neither an argument index nor a '<' flag. Each format specifier which uses ordinary indexing is assigned a sequential implicit index into argument list which is independent of the indices used by explicit or relative indexing.

formatter.format("%s %s %s %s", "a", "b", "c", "d") // -> "a b c d"

It is possible to have a format string which uses all forms of indexing, for example:

formatter.format("%2$s %s % "b a a b" // "c" and "d" are ignored because they are not referenced

The maximum number of arguments is limited by the maximum dimension of a Java array as defined by the Java Virtual Machine Specification. If the argument index is does not correspond to an available argument, then a MissingFormatArgumentException is thrown.

If there are more arguments than format specifiers, the extra arguments are ignored.

您所要求的是一种构建模式的方法,该模式将接受任意数量的参数并使用所有参数。问题在于 Formatter 类只能将格式说明符与参数显式、相对或普通地关联起来。在每种情况下,格式说明符的数量都是固定的。没有可以在其中重复或循环格式说明符的结构。相关技术看起来很有前途,但无法嵌套或循环。

关于Java格式化数组(使用Formatter类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7775574/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com