Cannot figure out how to format scanner input to two decimal places without getting this error

Viewed 18

Can someone lead me in the right direction or help me figure out why it's giving me the error of "100.0Exception in thread "main" 310.93 degrees in Fahrenheit isjava.util.MissingFormatArgumentException: Format specifier '%7.2f'? I'm a beginner in Java and can't seem to find a fix for this issue.


public static void main(String[] args) {
        // Below this comment: declare and instantiate a Scanner
          
          
        // Below this comment: declare any other variables you may need
        // to store the user's input and the Kelvin equivalent value
        

        // Below this comment: collect the requried inputs from the user
        System.out.println("Enter temperature in Fahrenheit : ");
        Scanner scan = new Scanner(System.in);
        float fahr = scan.nextFloat();
        // Below this comment: call your FahrenheitToKelvin method
        FahrenheitToKelvin(fahr);

        // Below this comment: disply the required results
        System.out.printf(fahr + "%.2f" + " degrees in Fahrenheit is%7.2f", FahrenheitToKelvin(fahr));
        System.out.printf(" degrees in Kelvin. ");
              
       }
       
       // define your FahrenheitToKelvin method here below
       public static float FahrenheitToKelvin(float fahr) {
          float kelv = (float) ((fahr - 32) * 5/9 + 273.15);
          return kelv;
      
    }
    }
1 Answers

This happens because in your printf you have 2 format specifiers (%.2f and %7.2f) and only one value (the result from FahrenheitToKelvin(fahr)).

Your code

System.out.printf(fahr + "%.2f" + " degrees in Fahrenheit is%7.2f", FahrenheitToKelvin(fahr));

has 3 strings, the fahr variable (which is a float, but gets converted here for the output because you concatenate it to a String), the "%.2f", and the " degrees in Fahrenheit is %7.2f". These get combined to one String before printf is called, e.g., to "123%.2f degrees Fahrenheit is %7.2f" if you enter 123. Now printf parses the String and sees two % markers for variables, but gets only the result of FahrenheitToKelvin(fahr) passed after the format string, and hence it throws an Exception which in turn crashes your program.

You can either just concatenate all numbers like this:

System.out.printf(fahr + " degrees in Fahrenheit is " + FahrenheitToKelvin(fahr));

and then also just use println instead of printf.

Or you can pass both numbers to printf, so that the number of % format specifiers matches the number of arguments:

System.out.printf("%.2f" + " degrees in Fahrenheit is%7.2f", fahr, FahrenheitToKelvin(fahr));

or, simpler and with a space before printing the result for legibility:

System.out.printf("%.2f degrees Fahrenheit is %7.2f degrees Kelvin", fahr, FahrenheitToKelvin(fahr));
Related