Java 格式字符串错误的参数太多

Java 格式字符串错误的参数太多,java,Java,我的格式字符串有问题 我得到的错误是格式字符串中的参数太多(找到9个,应该是8个)。我也尝试过重新格式化其他程序,但它们也给出了与此相同的错误 守则: public class FormattingOutput { public static void main(String args[]) { String module1Name = "Mathematics", module2Name = "Introduction to Programming", module3N

我的格式字符串有问题

我得到的错误是格式字符串中的参数太多(找到9个,应该是8个)。我也尝试过重新格式化其他程序,但它们也给出了与此相同的错误

守则:

public class FormattingOutput {
    public static void main(String args[]) {
        String module1Name = "Mathematics", module2Name = "Introduction to Programming", module3Name = "Web Design";
        int module1Students = 64, module2Students = 84, module3Students = 62;
        float module1Mark = 72.031f, module2Mark = 61.845f, module3Mark = 72.774f;

        String formatString = String.format("%-35s%-10d%.1f\n%-35s%-10d.1f\n%-35s%-10d%.1f",module1Name,module1Students,module1Mark,module2Name,module2Students,module2Mark,module3Name,module3Students,module3Mark);

        System.out.println("Module Name                     #Students   Average Mark\n"   + formatString);
    }
}
重新格式化它:

String formatString = String.format("
%-35s
%-10d
%.1f\n
%-35s
%-10d.1f\n
%-35s
%-10d
%.1f",
module1Name,
module1Students,
module1Mark,
module2Name,
module2Students,
module2Mark,
module3Name,
module3Students,
module3Mark);
您忘记了一个“%”字符,是不是:

String formatString = String.format("
%-35s
%-10d
%.1f\n
%-35s
%-10d
%.1f\n
%-35s
%-10d
%.1f",
module1Name,
module1Students,
module1Mark,
module2Name,
module2Students,
module2Mark,
module3Name,
module3Students,
module3Mark);

您有8%的字符,这意味着需要8个参数。
但是您提供了9

它看起来您的字符串在
.1f
前面缺少了一个
%
符号
“%-35s%-10d%.1f\n%-35s%-10d.1f\n%-35s%-10d%.1f”
应该是
“%-35s%-10d%.1f\n%-35s%-10d%.1f\n%-35s%-10d%.1f”

错误消息非常清楚,您有8%xxx并提供9个替换,因为除了第一个
字符串之外,您在对
String.format
的调用中指定了9个参数,然而,您在格式字符串中只指定了8个占位符。这是一个很好的捕获:)Jörns answr可能会让您感到更舒服,但在将来,如果您没有Björn的帮助,您也可以计算%的占位符