Reputation: 6078
What is a better way to get the same output as the following code, but without all the System.out
repeats?
Whenever I try to combine it all one one line, the printf
or println
wants something else and I get an error with Netbeans.
System.out.print("Thank you." + "\n" + "The resulting tip is ");
System.out.printf("%.2f", tip);
System.out.print(" and the total is ");
System.out.printf("%.2f", total);
System.out.println(".");
I'm trying to use the following on one line, how to include it on a single print attempt?
("Thank you." + "\n" + "The resulting tip is " + "%.2f", tip + "and the total is " %.2f", total + ".");
The program is a tip calculator, and I want to get the decimals rounded to two (ie xx.yy).
Upvotes: 1
Views: 6159
Reputation: 285405
System.out.printf("Thank you.%nThe resulting tip is %.2f and the total is %.2f%n.",
tip, total);
This the beauty of printf or System.format(...)
or String.format(...)
in that it allows you to use format specifiers in the String, and then list the corresponding variables at the end. Note that new lines should be "%n"
not "\n"
.
Upvotes: 3