2017-10-14 77 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的實現。