2017-04-25 58 views
1

我不斷收到此錯誤,說不兼容的類型: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

回答

1
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); 
1

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

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

變化

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 。不創建一個格式化與字符串

1

錯誤是由

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

造成如果你真的想返回此方法的字符串,然後嘗試

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

@ dawood-ibn-kareem感謝您的編輯。你結婚了,換了你的名字嗎? –

+0

不是最近。只是我的手柄在這裏。 –