2

Is there a way to conveniently use String.format (or printf) to print the values in an array. Example:

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

The output I'm looking for:

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

As the example suggests, I don't know how long the args array is? So far the only solution I've come up with is to first use .format to do get the first part of the string, then loop through the args array and append space separated chunks.

2 Answers 2

3

You have Arrays.toString(...), which will format it as ["unos", "dos", tres"], but I assume that is not what you want.

Usually I use the streaming api to collect the result into a string: 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(" ")));
}
Sign up to request clarification or add additional context in comments.

1 Comment

To clarify the edit undo: The %n in prinf means "use the platform specific code for going to a new line".
0

Since it is not a primitive array, you can wrap args in a list:

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

This then uses the implementation of toString for List.

Comments

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.