我目前正在尝试构建一个程序,该程序通过调用一个方法来打印不同高度的帕斯卡三角形,该方法使用一个用于三角形高度的 int 参数来构造三角形。当试图运行我的程序时,第一个 Pascal 的三角形打印 bu 然后我得到一个异常错误,读到:
java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0
at java.util.Formatter$FormatSpecifier.failMismatch(Unknown Source)
at java.util.Formatter$FormatSpecifier.checkBadFlags(Unknown Source)
at java.util.Formatter$FormatSpecifier.checkGeneral(Unknown Source)
at java.util.Formatter$FormatSpecifier.<init>(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at PascalsTriangle.drawTriangle(PascalsTriangle.java:19)
at PascalsTriangle.main(PascalsTriangle.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
通过调试,我注意到我如何格式化第 19 行中的字符串输出存在问题。我对 Java 编程相当陌生,我尝试在我的代码中解决不同的格式问题,但我一直不知道如何使这项工作。关于如何防止此异常错误发生的任何建议?
这是我的程序的代码:
public class PascalsTriangle {
private int height;
public void drawTriangle(int height) {
System.out.println("A Pascal Triangle with height " + height);
for(int i = 0; i <= height; i++) {
int number = 1;
System.out.format("%" + ((height-i) * 2) + "s", " ");
for(int j = 0; j <= i; j++) {
System.out.format("%5d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
public static void main(String[] args) {
PascalsTriangle pascal = new PascalsTriangle();
pascal.drawTriangle(4);
pascal.drawTriangle(10);
pascal.drawTriangle(7);
pascal.drawTriangle(2);
}
}