Java Printf格式错误不兼容的类型
我一直在说不兼容的类型:Java Printf格式错误不兼容的类型,java,printf,bluej,incompatibletypeerror,Java,Printf,Bluej,Incompatibletypeerror,我一直在说不兼容的类型:java.io.PrintStream无法转换为java.lang.String,我不知道如何让它在我的toString方法中工作。我试着将它赋给一个变量,然后返回它,然后计划将它作为一个返回语句打印出来,我没有发现printf格式有任何错误。谢谢你的帮助 import java.text.NumberFormat; public class Item { private String name; private dou
java.io.PrintStream无法转换为java.lang.String
,我不知道如何让它在我的toString方法中工作。我试着将它赋给一个变量,然后返回它,然后计划将它作为一个返回语句打印出来,我没有发现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
不返回字符串,您正在查找string.format
public String toString () {
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);
}
您正在尝试返回PrintStream
。这是不正确的,因为toString应该返回字符串
您应该使用方法,该方法在设置后返回一个字符串
return String.format("%-15s $%-8.2f %-11d $%-8.2f", name, price,
quantity, price*quantity);
您正在尝试返回PrintStream
。这是不正确的,因为toString应该返回字符串
您应该使用方法,该方法在设置后返回一个字符串
return String.format("%-15s $%-8.2f %-11d $%-8.2f", name, price,
quantity, price*quantity);
改变
到
因为System.out.println()
if用于将字符串打印到控制台。不创建格式化字符串-更改
System.out.printf("%-15s $%-8.2f %-11d $%-8.2f", name, price,
quantity, price*quantity);
到
因为
System.out.println()
if用于将字符串打印到控制台。不创建格式化字符串-错误是由
return System.out.printf(....)
如果您确实想从该方法返回字符串,请尝试
return String.format(....);
错误是由以下原因引起的:
return System.out.printf(....)
如果您确实想从该方法返回字符串,请尝试
return String.format(....);
您尝试将双精度打印为浮点,双精度使用
d
,浮点使用f
您尝试将双精度打印为浮点,双精度使用d
,浮点使用f
floats@dawood-伊本·卡里姆:谢谢你的编辑。你结婚并改名了吗?不是最近。这里只有我的把柄。@dawood ibn kareem谢谢你的编辑。你结婚并改名了吗?不是最近。这就是我的把手。