barbara
barbara

Reputation: 3201

How can I exclude parameter from the format expression when option is null?

Here is my java code

System.out.format("a: %s b: %s c: %s", s1, s2, s3);

If s2 is null, I want to print a: <val> c: <val> without b: null. If s3 or any other param is null I want to skip it as well.

Seams that it should be some tricky expression.

UPDATE

Without if/else logic! Only using expressions inside of format method.

Upvotes: 1

Views: 86

Answers (2)

RealSkeptic
RealSkeptic

Reputation: 34638

If you insist on a one-liner here is a possibility:

    System.out.format(
            (( s1 == null ? "" : "a: %1$s" )
            + ( s2 == null ? "" : " b: %2$s" )
            + ( s3 == null ? "" : " c: %3$s" )).trim(),
            s1, s2, s3
    );

(Yeah, not technically a one-liner, but one statement).

The idea: build the format string based on whether or not a given string is null. The trim() is there to get rid of the initial space before b: or c: in case s1 was null.

Upvotes: 1

Martin v. L&#246;wis
Martin v. L&#246;wis

Reputation: 127527

It seems easier to break this into three calls

System.out.format("a: %s", s1);
if (s != null)
    System.out.format(" b: %s", s2);
System.out.format(" c: %s", s3);

If you absolutely wanted to put this into a single call, something like

System.out.format("a: %s%s%s c: %s", s1,
    (s2==null)?"":" b: ",
    (s2==null)?"":s2,
    s3);

could also work.

Upvotes: 1

Related Questions