PrintStream类型中的printf(String,Object )方法不适用于参数(…)

为什么我通过简单的printf调用得到以下编译错误? 我的代码:

import java.util.Scanner; public class TestCodeBankAccInputs { public static void main(String[] args) { String displayName = "Bank of America Checking"; int balance = 100; System.out.printf("%s has %7.2f", displayName, balance); } } 

在编译时我收到以下错误:

 Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, String, double) at TestCodeBankAccInputs.main(TestCodeBankAccInputs.java:9) 

造成这种情况的原因是什么?如何解决?

版本信息:

在Eclipse中帮助 – >关于提供以下信息:

面向Web开发人员的Eclipse Java EE IDE。

版本:Indigo Release Build id:20110615-0604

我安装的JDK是JDK1.6.0_27

我已经看到了关于String.format的类似问题 。 一些用户建议它可能是构建问题,但看起来我已经更新了版本。

检查项目的Compiler compliance level是否设置为至少1.5:

项目>属性> Java编译器

如果未设置Enable project specific settings ,请使用Configue Workspace Settings...链接检查全局Compiler compliance level

在此处输入图像描述

这似乎很奇怪,它再次出现(与您链接的其他post相同)。 我想知道最近版本的Eclipse中是否存在错误? 那个post上的提问者再也没有回来了,所以我怀疑它可能刚刚消失了。 你的代码完美无缺。 如果我提供了一个合适的BankAccount类,它将在IntelliJ 10.5.2和javacjava版本1.6.0_26的命令行中按预期编译和运行:

 import java.util.Scanner; public class TestCodeBankAccInputs { public static void main(String[] args) { Scanner inStream = new Scanner(System.in); BankAccount myAccount = new BankAccount(100, "Bank of America Checking"); System.out.print("Enter a amount: "); double newDeposit = inStream.nextDouble(); myAccount.deposit(newDeposit); System.out.printf("%s has %9.2f", myAccount.displayName(), myAccount.getBalance()); //System.out.printf("%3s", "abc"); } static class BankAccount { private double balance; private String name; public BankAccount(double balance, String name) { this.balance = balance; this.name = name; } public String displayName() { return name; } public double getBalance() { return balance; } public void deposit(double newDeposit) { this.balance += newDeposit; } } } 

我仍然(正如我在其他post中所做的那样)推荐一个干净的构建,但是你在Eclipse中检查了你的编译器合规级别吗? 您可以使用1.6 JDK进行编译,但仍然可以在IDE中设置较低的合规性级别,这可以使有趣的事情发生。

使用: System.out.printf(arg0, arg1, arg2)而不是System.out.printf(arg0, arg1)

像这样的临时修复可能会起作用。

而不是使用printf ,使用此:

 System.out.printf("%s has %7.2f", new Object[]{ myAccount.displayName(), myAccount.getBalance() } ); 

这可能会解决您的问题。