Java 我做错了什么?
类是Product,方法是getName、getPrice和reducePrice: 我已经创建了构造函数和方法,但不明白为什么我的实例变量private string name出现错误,以及如何为我的方法创建getName和getPrice主体。我还没有创建我的ProductTester来实际打印结果,可以使用我能得到的所有建议Java 我做错了什么?,java,eclipse,methods,Java,Eclipse,Methods,类是Product,方法是getName、getPrice和reducePrice: 我已经创建了构造函数和方法,但不明白为什么我的实例变量private string name出现错误,以及如何为我的方法创建getName和getPrice主体。我还没有创建我的ProductTester来实际打印结果,可以使用我能得到的所有建议 public class Product { private double price; private string name; // this
public class Product
{
private double price;
private string name; // this has an error???
/**
Constructs a product with a given name and price.
@param name the name
@param price the price
*/
public Product(String n, double p)
{n = name;
p = price;}
/**
Gets the product name.
@return the name
*/
public String getName() // what is the body??
{ }
/**
Gets the product price.
@return the price
*/
public double getPrice() // what is the body???
{ }
/**
Reduces the product price.
@param amount the amount by which to reduce the price
*/
public void reducePrice(double amount)
{ price = price - amount;}
}
修订类别产品:
}
这是我的ProductPrinter课程。制作两个产品,打印名称和价格,将价格降低5,然后再次打印:system.out.printlnmyProducts.reducePrice5和system.out.printlnmyProducts2.reducePrice5有错误
您正在使用字符串而不是字符串
所以把这个
private String name;
并且在方法getName和getPrice中没有返回所需的值
他们完全错了:
public Product(String n, double p)
{name = n;
price = p;}
那就好了
错误:
private String name;
应该修复错误
方法体:您只需要在此处返回变量:
public String getName() // what is the body??
{
return name;
}
/**
Gets the product price.
@return the price
*/
public double getPrice() // what is the body???
{
return price;
}
首先,它是字符串而不是字符串:
在constructorpublic产品{}中,您做错了!您可能希望设置name=n和price=p,以便稍后在程序中使用:
public Product(String n, double p){
name = n;
price = p;
}
对于getName和getPrice方法,您只需要返回适当的值:
public String getName(){
return name;
}
public double getPrice(){
return price;
}
将reducePrice方法替换为below方法,因为此方法不返回任何值,因此无法从System.out.println调用void方法
public double reducePrice(double amount)
{
return price = price - amount;
}
将构造函数方法替换为下面的方法-
public Product(String n, double p)
{
name = n; // n = name is not correct as you are assigning name value into your local variable n
price = p; // p = price , same case with price variable also
}
字符串的大写字母“s”可能是..注意:use name=n;而不是n=名称;在问这个问题之前,你应该真正了解语言的基本知识。
private String name; // Note the capital 'S'
public Product(String n, double p){
name = n;
price = p;
}
public String getName(){
return name;
}
public double getPrice(){
return price;
}
public double reducePrice(double amount)
{
return price = price - amount;
}
public Product(String n, double p)
{
name = n; // n = name is not correct as you are assigning name value into your local variable n
price = p; // p = price , same case with price variable also
}