Reputation: 173
Having a little bit of trouble in Java here with my printf statement. My code works properly, as I have tested it with println, I just need to get my spacing correct which is why I need to use printf. I've tried numerous ways of spacing and separating my strings and variables. I think part of the issue is that I have to use the "$" and that is messing with the printf statement. This is part of a school project so that is why I have to use printf instead of just doing a println statment. My code is as follows
for(double ten = 10.00; ten < 15.00; ten = ten + .75){
/**
* We use the variable tip to calculate a %20 tip and we use the
* variable totalWithTip to calculate the total of the dinner price
* and the tip added together.
*/
double tip = ten * .2;
double totalWithTip = ten + tip;
System.out.printf("$%7s%4.2d$%13s%4.2d$%13s%4.2d\n", ten, tip, totalWithTip);
}
I need the output to look like
Dinner Price 20% tip Total
---------------------------------------------------
$10.00 $ 2.00 $12.00
$10.75 $ 2.15 $12.90
$11.50 $ 2.30 $13.80
$12.25 $ 2.45 $14.70
$13.00 $ 2.60 $15.60
$13.75 $ 2.75 $16.50
$14.50 $ 2.90 $17.40
Upvotes: 1
Views: 275
Reputation: 1608
In your case, this might be a solution:
System.out.printf("%7s$%4.2f%13s$ %4.2f%13s$%4.2f\n"," ", ten, " ", tip, " ", totalWithTip);
In your example, the spaces were put after data. Also, you just need %f for a double (or float), with the .2 specifying the decimal places.
Upvotes: 2
Reputation: 321
Another alternative:
System.out.printf("%7s$%-13.2f$%-13.2f$%-13.2f\n", " ", ten, tip, totalWithTip);
The '-' aligns the output of the parameter to the left and adds padding characters to the right.
Upvotes: 2
Reputation: 2166
System.out.printf("$%.2f $%.2f $%.2f \n", ten, tip, totalWithTip);
You just need %f for a double (or float), with the .2 specifying the decimal places.
For the spaces, you use the 'c' character, prefixed with the number of spaces. E.g. %6c will print 6 characters.
System.out.printf("$%.2f%6c$%.2f%6c$%.2f\n", ten, ' ', tip,' ',totalWithTip);
Upvotes: 3