0

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

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Or just System.out.print(s + " ") which does the same as System.out.format("%d ", s), but without cryptic placeholders.
Yeah thats right. Also there are other 'nicer' ways to fulfill the origin task. But the question starts with the preamble '...we need to use format() method ...'
Actually, the question starts with “I know, we need to use format()”, which sounds like a wrong assumption or half-knowledge, as we do not need to use format(), due to the existence of alternatives.
2

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

2 Comments

@erickson You are welcome :-) I used this class because the array of ints and to avoid the problem of the dangerous invisible whitespace after the last element of the array, it is also very useful for logging.
That’s what you also get when using String spaceSeparatedNumbers = Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(" "));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.