简体   繁体   中英

I don't know what's wrong with one of my variable.[Exception in thread “main” java.util.UnknownFormatConversionException: Conversion = 'm']

import java.util.Scanner;

public class LABEX03
{
    public static void main(String[] args)
    { 
            System.out.println("Name LE01");
            Scanner kbd = new Scanner(System.in);
            double m = 3;
            double n = 0;
            System.out.print("type 12 and Press enter");
            n = kbd.nextInt();
            double p = (double)m * (double)n;
            double q = 0;
            q = (double)Math.sqrt(p);
            System.out.printf("%m");
            System.out.printf("%n");
            System.out.printf("%p");
            System.out.printf("%q");
    }
} 

Debug:

Name LE01 type 12 and Press enter12 Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'm' at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2691) at java.util.Formatter$FormatSpecifier.(Formatter.java:2720) at java.util.Formatter.parse(Formatter.java:2560) at java.util.Formatter.format(Formatter.java:2501) at java.io.PrintStream.format(PrintStream.java:970) at java.io.PrintStream.printf(PrintStream.java:871) at LABEX03.main(LABEX03.java:16) Java Result: 1 BUILD SUCCESSFUL (total time: 6 seconds)

You've misunderstood what is supposed to be in the format string with the % signs. The variable names don't go in the format string, they are passed as separate parameters to printf . The format specifier indicates the type of the variable passed in, eg %d for integers, %f for floating-point numbers, and %s for string text.

Try eg:

System.out.printf("%f", m);

For further reference, see the Formatter javadocs , which gives more detail about how to format your strings and pass in variables.

Your format statements aren't correct.

// Should print "q=2.0"
double q = Math.sqrt(4.0);
System.out.printf ("q=%g", q);

Here's the Javadoc:

http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

You seem to be confused about the number and order of parameters for printf . I'm fairly certain you wanted something like,

System.out.printf("m = %f%n", m);
System.out.printf("n = %f%n", n);
System.out.printf("p = %f%n", p);
System.out.printf("q = %f%n", q);

When I run your code (with the above change) and input 12 I get

m = 3.000000
n = 12.000000
p = 36.000000
q = 6.000000
System.out.printf("m = %f", m);
System.out.printf("n = %f", n);
System.out.printf("p = %f", p);
System.out.printf("q = %f", q);

I was able to change the (Int) into (Doubles) and change ("%m") into ("m = %f", m). It worked well. Thanks everyone for the helpful tips

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM