比如Java自己的String.format()
支持可变数量的参数。
String.format("Hello %s! ABC %d!", "World", 123);
//=> Hello World! ABC 123!
如何创建自己的函数来接受可变数量的参数?
后续问题:
我真的想为此创建一个方便的快捷方式:
System.out.println( String.format("...", a, b, c) );
这样我就可以将其称为不太冗长的东西,如下所示:
print("...", a, b, c);
我怎样才能实现这个目标?
你可以写一个方便的方法:
public PrintStream print(String format, Object... arguments) {
return System.out.format(format, arguments);
}
但正如你所看到的,你只是简单地重命名了format
(or 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();
// 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
注意还有类似的System.out.printf
方法的行为方式相同,但如果你看一下实现,printf
只是打电话format
,所以你不妨使用format
直接地。
- Varargs http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
- PrintStream#format(String format, Object... args) http://download.oracle.com/javase/7/docs/api/java/io/PrintStream.html#format%28java.lang.String,%20java.lang.Object...%29
- PrintStream#printf(String format, Object... args) http://download.oracle.com/javase/7/docs/api/java/io/PrintStream.html#printf%28java.lang.String,%20java.lang.Object...%29
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)