繁体   English   中英

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

[英]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 中以及从命令行使用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;
        }
    }
}

我仍然(就像我在另一篇文章中所做的那样)推荐一个干净的构建,但是您是否检查过 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM