Rather than building your string as a single expression of the form ... + ... + ...
, you can use a StringBuilder
(see Javadoc for java.lang.StringBuilder
) to assemble it across several statements. For example, something like this:
JOptionPane.showMessageDialog(null, "foo: " + 17 + "\n" + "bar" + 18 + "\n");
can be rewritten like this:
StringBuilder message = new StringBuilder();
message.append("foo: ").append(17).append("\n");
message.append("bar: ").append(18).append("\n");
JOptionPane.showMessageDialog(null, message.toString());
By using this approach, you can wrap any of the individual "append" statements in an if
-block that makes sure the value is nonzero before adding it to the string.