[英]The method printf(String, Object…) in the type PrintStream is not applicable for the arguments (String, void)
[英]The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (...)
為什么通過簡單調用 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 中的 Help->About 提供以下信息:
面向 Web 開發人員的 Eclipse Java EE IDE。
版本:Indigo 發布版本 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
。
這似乎很奇怪,這又出現了(與您鏈接的其他帖子相同的問題)。 我想知道最近版本的 Eclipse 中是否有錯誤? 另一篇文章的提問者再也沒有回來提供更多信息,所以我懷疑它可能剛剛消失了。 您的代碼運行良好。 如果我提供適當的 BankAccount 類,它會在 IntelliJ 10.5.2 中以及從命令行使用javac
和java
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;
}
}
}
我仍然(就像我在另一篇文章中所做的那樣)推薦一個干凈的構建,但是您是否檢查過 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()
} );
這可能會解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.