我遇到了格式说明符的问题.这是否意味着我使用的%d?
public static void main(String[] args)
{
double y, x;
for (x = 1.0; x <= 7.0; x+=0.1)
{
y = x * x - 5 * x + 6;
System.out.printf("x = "+x+", y = %d", y);
System.out.printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
这就是代码,这里是输出:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double
x = 1.0, y = at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2748)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2702)
at java.util.Formatter.format(Formatter.java:2488)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at wilson_hw03a.java.Wilson_hw03aJava.main(Wilson_hw03aJava.java:15)
Java Result: 1
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?更好的是,错误是什么?
没有"NetBeans"错误,程序中存在Java错误.你在printf语句的错误部分有一个格式说明符.它必须位于String中,它是第一个参数的一部分,在分隔方法参数的逗号之前.所以不是这样的:
System.out.printf("x = "+x+", y = %d", y);
Run Code Online (Sandbox Code Playgroud)
而是这个:
System.out.printf("x = %d, y = %d", x, y);
Run Code Online (Sandbox Code Playgroud)
或者如果你想要一个新行:
System.out.printf("x = %d, y = %d%n", x, y);
Run Code Online (Sandbox Code Playgroud)
请注意,在printf或String.format(...)语句中,%n不要\n用于换行.
小智 5
我刚刚注意到另一个问题.double的格式说明符是%f和不是%d.它也可能导致FormatSpecifier错误.
public static void main(String[] args) {
double y, x;
for (x = 1.0; x <= 7.0; x += 0.1) {
y = x * x - 5 * x + 6;
System.out.printf("x = %f, y = %f", x, y); // or
System.out.printf("x = %f, y = %f%n", x, y);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1850 次 |
| 最近记录: |