Evan Li
Evan Li

Reputation: 33

Java: System.out.format IllegalFormatPrecision Exception

Consider the following loop to print a chart: Assuming that all elements in the array as well as interest have an assigned value, why would the for loop (the System.out.format, to be exact) yield an IllegalFormatPrecisionException?

   double[] sbalance; 
   double[] fbalance; 
   double[] interest; 
   sbalance = new double[months]; 
   fbalance = new double[months]; 
   interest = new double[months];  
   int deposit; 
    for (int q = 1; q <= months; q++)
   {
       System.out.format ("%18.2d%", sbalance[q-1]); 
       System.out.format ("%18.2d%", interest [q-1]); 
       System.out.format ("%18.2d%", (double)deposit);
       System.out.format ("%18.2d%", fbalance [q-1]); 
    }

Even if I go back and redeclare my arrays as Double[] instead of double[], the program yields the same error (I realise that java is inconsistent about autoboxing)

Any help is much appreciated.

Upvotes: 0

Views: 195

Answers (3)

mernst
mernst

Reputation: 8117

There are two problems.

  1. In the format string, %18.2d should be %18.2f.
  2. At the end of the format string, % should be %n. (In cron files, % means newline, but in Java, %n means newline.)

Here is working code:

public class Interest {

  public static void main(String[] args) {
    int months = 12;
    int deposit = 1000;

    double[] sbalance; 
    double[] fbalance; 
    double[] interest; 
    sbalance = new double[months]; 
    fbalance = new double[months]; 
    interest = new double[months];  
    for (int q = 1; q <= months; q++) {
      System.out.format ("Month %d%n", q); 
      System.out.format ("%18.2f%n", sbalance[q-1]); 
      System.out.format ("%18.2f%n", interest [q-1]); 
      System.out.format ("%18.2f%n", (double)deposit);
      System.out.format ("%18.2f%n", fbalance [q-1]); 
    }

  }

}

If you want to be warned of IllegalFormatPrecision errors at compile time rather than suffering a run-time crash, you can use the Format String Checker of the Checker Framework. If you had installed it and run

$CHECKERFRAMEWORK/checker/bin/javac -processor formatter Interest.java

then the compiler would have warned you about your problems with specific error messages.

Upvotes: 2

paf.goncalves
paf.goncalves

Reputation: 488

The d in the format means decimal integer, not a double. You should use a f.

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140309

Use %f instead of %d.

The former formats floating point numbers; the latter formats integers. It makes no sense to ask to print an integer with 2 decimal places.

Upvotes: 2

Related Questions