如何创建接受可变数量参数的Java方法? [英] How to create Java method that accepts variable number of arguments?
问题描述
String.format()
支持可变数量的参数。 String.format(Hello%s!ABC%d!,World,123);
// =>你好,世界! ABC 123!
如何让我自己的函数接受可变数量的参数?
后续问题:
我真的想做一个方便的捷径为此:
System.out.println(String.format(...,a,b,c)) ;
因此,我可以将它称为不像以下这样冗长的内容:
print(...,a,b,c);
我该如何做到这一点?
preublic $ PrintStream print(String format,Object。 .. arguments){
return System.out.format(format,arguments);
}
但是,正如您所看到的,您只是简单地将 format
(或 printf
)。
以下是您可以如何使用它的方法:
private void printScores(Player ... players){
for(int i = 0; i< players .length; ++ i){
Player player = players [i];
String name = player.getName();
int score = player.getScore();
//打印名称和分数,然后换行符
System.out.format(%s:%d%n,name,score);
}
}
//打印单个玩家,3个玩家和所有玩家
printScores(player1);
System.out.println();
printScores(player2,player3,player4);
System.out.println();
printScores(playersArray);
//输出
Abe:11
Bob:22
Cal:33
Dan:44
Abe:11
Bob:22
Cal:33
Dan:44
$ b $注意,还有类似的 System.out.printf
方法的行为方式相同,但是如果您仔细查看实现, printf
只是调用 format
,所以你可以直接使用 format
。
- Varargs
-
PrintStream#format(String format,Object ... args)
-
PrintStream#printf(String format,Object ... args)
For example, Java's own String.format()
supports a variable number of arguments.
String.format("Hello %s! ABC %d!", "World", 123);
//=> Hello World! ABC 123!
How can I make my own function that accepts a variable number of arguments?
Follow-up question:
I'm really trying to make a convenience shortcut for this:
System.out.println( String.format("...", a, b, c) );
So that I can call it as something less verbose like this:
print("...", a, b, c);
How can I achieve this?
You could write a convenience method:
public PrintStream print(String format, Object... arguments) {
return System.out.format(format, arguments);
}
But as you can see, you've simply just renamed format
(or printf
).
Here's how you could use it:
private void printScores(Player... players) {
for (int i = 0; i < players.length; ++i) {
Player player = players[i];
String name = player.getName();
int score = player.getScore();
// Print name and score followed by a newline
System.out.format("%s: %d%n", name, score);
}
}
// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);
// Output
Abe: 11
Bob: 22
Cal: 33
Dan: 44
Abe: 11
Bob: 22
Cal: 33
Dan: 44
Note there's also the similar System.out.printf
method that behaves the same way, but if you peek at the implementation, printf
just calls format
, so you might as well use format
directly.
- Varargs
PrintStream#format(String format, Object... args)
PrintStream#printf(String format, Object... args)
这篇关于如何创建接受可变数量参数的Java方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!