java方法参数数量,如何创建一个接受可变数量参数的Java方法?

本文介绍如何在Java中创建一个接受可变数量参数的便捷方法,类似于String.format()的功能,简化System.out.println(String.format())的使用。通过提供一个便利方法print(),可以直接传入格式字符串和参数,实现更简洁的输出。
摘要由CSDN通过智能技术生成

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值