Reputation: 146
I know, we need to use fortmat() method while formatting the output. 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. something like 38 27 43 3 9 82 10
Upvotes: 0
Views: 263
Reputation: 4572
If you want a space separator between elements of your int array it is possible use the StringJoiner
class like below:
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
Upvotes: 2
Reputation: 1170
System.out.format()
works with placeholders. So the %d
stands for a 'decimalValue' that you give him afterwards. With the number you can specify the 'width' of the placeholder. So %3d
will always have at least 3 width. Docs.
If you only want to output the value with one space between make something like:
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.
Upvotes: 4