Printf 格式化错误不兼容的类型

Printf formatting error incompatible types

我不断收到此错误,提示类型不兼容:java.io.PrintStream cannot be converted to java.lang.String,而且我不知道如何让它为我的 toString 方法工作。我试过将它分配给一个变量,然后 returning 它,然后只是计划将它作为 return 语句打印出来,我没有发现我的 printf 格式有任何问题。感谢帮助。

 import java.text.NumberFormat;

    public class Item
    {
        private String name;
        private double price;
        private int quantity;


        // -------------------------------------------------------
        //  Create a new item with the given attributes.
        // -------------------------------------------------------
        public Item (String itemName, double itemPrice, int numPurchased)
        {
        name = itemName;
        price = itemPrice;
        quantity = numPurchased;
        }


        // -------------------------------------------------------
        //   Return a string with the information about the item
        // -------------------------------------------------------
        public String toString ()
        {

        return System.out.printf("%-15s $%-8.2f %-11d $%-8.2f", name, price, 
     quantity, price*quantity);
        }

        // -------------------------------------------------
        //   Returns the unit price of the item
        // -------------------------------------------------
        public double getPrice()
        {
        return price;
        }

        // -------------------------------------------------
        //   Returns the name of the item
        // -------------------------------------------------
        public String getName()
        {
        return name;
        }

        // -------------------------------------------------
        //   Returns the quantity of the item
        // -------------------------------------------------
        public int getQuantity()
        {
        return quantity;
        }
    }  

System.out.printf 不是 return 字符串,您正在寻找 String.format

public String toString () {
    return String.format("%-15s $%-8.2f %-11d $%-8.2f", name, price, quantity, price*quantity);
}
 return System.out.printf("%-15s $%-8.2f %-11d $%-8.2f", name, price, 
     quantity, price*quantity);

您正在尝试 return PrintStream。这是不正确的,因为 toString 应该 return 一个字符串。

你应该使用 String#format 方法,它在格式化后返回一个字符串

return String.format("%-15s $%-8.2f %-11d $%-8.2f", name, price, 
         quantity, price*quantity);

改变

 System.out.printf("%-15s $%-8.2f %-11d $%-8.2f", name, price, 
 quantity, price*quantity);

 String.format("%-15s $%-8.2f %-11d $%-8.2f", name, price, 
 quantity, price*quantity);

因为 System.out.println() 如果要打印字符串到控制台。不创建格式化字符串-

错误是由

引起的
return System.out.printf(....)

如果你真的想return从这个方法中得到一个字符串,那么试试

return String.format(....);