Printf格式错误不兼容的类型

Printf格式错误不兼容的类型

问题描述:

我不断收到此错误,说不兼容的类型:java.io.PrintStream cannot be converted to java.lang.String,我没有得到如何让它为我的toString方法工作。我试着把它分配给一个变量,然后返回它,然后只是打算把它打印出来作为返回语句,我没有发现我的printf格式有什么问题。帮助表示赞赏。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; 
     } 
    } 
+0

你要打印一个双象一个浮动,使用'd'为双打,'f'为浮动 – Ferrybig

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

你试图返回PrintStream。这是不正确的,因为toString应该返回一个String。

你应该使用String#format方法,其中fomratting

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

System.out.printf不返回一个字符串,您正在寻找String.format

public String toString() { 
    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()如果打印字符串到控制台后还给一个String 。不创建一个格式化与字符串

错误是由

return System.out.printf(....) 

造成如果你真的想返回此方法的字符串,然后尝试

return String.format(....); 
+1

@ dawood-ibn-kareem感谢您的编辑。你结婚了,换了你的名字吗? –

+0

不是最近。只是我的手柄在这里。 –