Dylan Kelemen Dylan Kelemen - 1 month ago 26
Java Question

Printf issues in Java

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

Answer

In your case, this might be a solution:

System.out.printf("%7s$%4.2f%13s$%4.2f%13s$%4.2f\n"," ",  ten, " ", tip, " ", totalWithTip);