2017-10-14 47 views
1

有没有一种方法可以方便地使用String.format(或printf)打印数组中的值。例如:String.format和数组

public static void main(String[] args) { 
    System.out.printf("Today is %tc and your args are %TAG", new Date(), args); 
} 

我在寻找的输出:

Today is Sat Oct 14 14:54:51 CEST 2017 and your args are uno dos tres 

正如例子表明,我不知道args阵列是多久?到目前为止,我提出的唯一解决方案是首先使用.format来获取字符串的第一部分,然后遍历args数组并追加空格分隔的块。

回答

2

你有,将其格式化为[“UNOS”,“DOS”,TRES“],但我认为这不是你想要的。

我通常使用流API收集结果转换成字符串: Arrays.stream(args).collect(Collectors.joining(" "));

public static void main(String[] args) { 
    System.out.printf("Today is %tc and your args are %s%n", new Date(), 
    Arrays.stream(args).collect(Collectors.joining(" "))); 
} 
+0

澄清编辑撤销:prinf中的%n表示“使用特定于平台的代码去换行”。 –

0

由于它不是一个基本类型数组,你可以在列表中包裹args

System.out.printf("%Tc %s", new Date(), Arrays.asList(args)); 

然后对List使用toString的实现。