简体   繁体   English

Java 数组 output 格式化

[英]Java array output formatting

I know, we need to use fortmat() method while formatting the output.我知道,我们在格式化 output 时需要使用 format() 方法。 Here is my below code:这是我的以下代码:

int arr[] = { 38, 27, 43, 3, 9, 82, 10 };
    Arrays.stream(arr).forEach(s -> System.out.format("%2d", s));
//output     382743 3 98210

If i use below code:如果我使用下面的代码:

Arrays.stream(arr).forEach(s -> System.out.format("%3d", s));
//output  38 27 43  3  9 82 10

I want to print the output only with one space between the next value.我想打印 output ,下一个值之间只有一个空格。 something like 38 27 43 3 9 82 10像 38 27 43 3 9 82 10

System.out.format() works with placeholders. System.out.format()与占位符一起使用。 So the %d stands for a 'decimalValue' that you give him afterwards.所以%d代表你之后给他的'decimalValue'。 With the number you can specify the 'width' of the placeholder.您可以使用数字指定占位符的“宽度”。 So %3d will always have at least 3 width.所以%3d总是至少有 3 个宽度。 Docs . 文档

If you only want to output the value with one space between make something like:如果您只想 output 之间有一个空格的值,请执行以下操作:

Arrays.stream(arr).forEach(s -> System.out.format("%d ", s));

Then you will put the decimalValue (without specifying a width) and a " " (space) afterwards, foreach entry in the array.然后,您将在数组中为每个条目放置十进制值(不指定宽度)和一个“”(空格)。

If you want a space separator between elements of your int array it is possible use the StringJoiner class like below:如果您想在 int 数组的元素之间使用空格分隔符,可以使用StringJoiner class ,如下所示:

int arr[] = { 38, 27, 43, 3, 9, 82, 10 };
StringJoiner sj = new StringJoiner(" ");
for (int i : arr) { sj.add(String.valueOf(i)); }
String spaceSeparatedNumbers = sj.toString();
System.out.println(spaceSeparatedNumbers); //<-- 38 27 43 3 9 82 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM