Search code examples
javajgrasp

Exception in thread "main" java.util.IllegalFormatPrecisionException: 2, tried to fix the formatting but did not work jGRASP


I am trying to make a program which averages two numbers.

public class Average
{
   private double one, two, average;
   public void setNums(double num1, double num2)
    {
      one=num1;
      two=num2;
    }

    public void average( )
    {
      average = (one + two) / 2;

    }
    public void print()
    {
      System.out.print( one+" + "+two +"has an average of ");
      System.out.printf("%.2d\n",average);
    }
}

This is the error that comes out, I assume that its due to the formatting.

Exception in thread "main" java.util.IllegalFormatPrecisionException: 2 at java.base/java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:3138) at java.base/java.util.Formatter$FormatSpecifier.(Formatter.java:2874) at java.base/java.util.Formatter.parse(Formatter.java:2713) at java.base/java.util.Formatter.format(Formatter.java:2655) at java.base/java.io.PrintStream.format(PrintStream.java:1209) at java.base/java.io.PrintStream.printf(PrintStream.java:1105) at Average.print(Average.java:26) at AverageRunner.main(AverageRunner.java:17) ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete.

Help pls.

Also, it compiles fine but inside the main method it will not run.


Solution

  • The issue is with this line:

      System.out.printf("%.2d\n",average);
    

    "%.2d\n" is a malformed format string for double. Replace it with "%.2f\n"