該類是產品,方法是getName,getPrice和reducePrice: 我已經創建了構造函數和方法,但無法弄清楚爲什麼我的實例變量私有字符串名稱出現錯誤,如何創建getName和getPrice身體爲我的方法。我還沒有創建我的ProductTester來實際打印結果,可以使用我可以獲得的所有建議。我在做什麼錯?
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;}
}
修訂的類產品:
public class Product
{
private double price;
private String name;
/**
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()
{ return name;}
/**
Gets the product price.
@return the price
*/
public double getPrice()
{ return price; }
/**
Reduces the product price.
@param amount the amount by which to reduce the price
*/
public void reducePrice(double amount)
{ price = price - amount;}
public double price()
{ return price;}
}
這是我ProductPrinter類。製作兩個產品,打印名稱和價格,將價格降低5,然後重新打印:我在system.out.println(myProducts.reducePrice(5))和system.out.println(myProducts2.reducePrice(5) ))。
/** A class to test the Product class
*/
public class ProductPrinter
{
/** Tests the methods of the Product class.
* @param args not used
*/
public static void main(String[] args)
{
Product myProducts = new Product("TV", 499.00);
Product myProducts2 = new Product("Bed", 899.00);
System.out.println(myProducts.getName());
System.out.println(myProducts2.getName());
System.out.println(myProducts.getPrice());
System.out.println(myProducts2.getPrice());
System.out.println(myProducts.reducePrice(5));
System.out.println(myProducts2.reducePrice(5));
System.out.println(myProducts.price());
System.out.println(myProducts2.price());
}
}
資本的「絃樂也許是吧.. – Revive 2014-09-30 20:43:05
注:使用'名稱= N;',而不是'N =名稱;' – Krayo 2014-09-30 20:45:58
在問這個問題之前,你應該真的瞭解這門語言的基礎知識。 – manouti 2014-09-30 20:49:45