Question

I have a question on how I am supposed to use printf for a mix of multiple formats. In my case, I am trying to give a number a certain amount of spaces so that it fits perfectly In a table and I am trying to limit how many decimal places it is allowed. Below is what I have tried with printf:

System.out.printf("%1s%10s%27s%26s%28s%28s1.5d", typeOCar, startingMiles, endingMiles, Distance, gallons, MPG);

when I execute my program, it displays this:

run:
                                                 Gas & Mileage Calculations

Car Type           Starting Miles             Ending Miles                 Distance                  Gallons             Miles/Gallon
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Toyota Sequoia     15543                      15565                        22                        16.5          1.33333333333333331.5dBUILD SUCCESSFUL (total time: 0 seconds)

Any help will be greatly appreciated.

Was it helpful?

Solution

  1. Your last format specifier should be an f for floating point number using width and precision numbers: e.g., %20.5f
  2. Many of your String specifiers, %xs, should likely be decimal specifiers, %xd where x is the format width.
  3. If you make this change, then the corresponding argument should be a decimal number, not a String.
  4. You have too many format specifiers for the number of arguments you pass in. This is nothing but basic math. Count your specifiers and your parameters.
  5. Read the Formatter API for all the details.

OTHER TIPS

import java.text.DecimalFormat;

then use this in your code:

DecimalFormat fmt = new DecimalFormat("00.##"); //0 = numbers before . and # numbers after .

and to convert any value (example here being printed out directly):

System.out.println(fmt.format(varName));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top