2017-02-14 72 views
-2

(对于我的记录,我仍然是编程新手)因此,对于我的CS类中的一个,我们有这个项目,其中的一部分是不得不打印出课程的属性,而且我很难做到这一点?真的很感激帮助我敢肯定它可能是简单的,但我一直都用它挣扎了一会儿如何从一个类打印属性?

public class Product { 
private int ProductId; 
private String Description; 
private double Price; 

public Product(int pID, String description, double price) { 

    ProductId = pID; 
    Description = description; 
    Price = price; 


} 

public int getProductID() { 
    return this.ProductId; 

} 

public void setProductID(int input) { 
    this.ProductId = input; 
} 



public String getDescription() { 

    return this.Description; 
} 

public void setDescription(String DescriptionInput) { 
    this.Description = DescriptionInput; 
} 




public double getPrice() { 
    return this.Price; 
} 

public void setPrice(double priceInput) { 
    this.Price = priceInput; 
} 

}

+0

到目前为止你有什么尝试? –

+0

尝试搜索之前张贴!这个问题以前肯定有人问过。 –

+0

在Java API中查看'System.out.println()' – Lopan

回答

1

我已经为你实现了toString方法。

public class Product { 
    private int ProductId; 
    private String Description; 
    private double Price; 

public Product(int pID, String description, double price) { 

    ProductId = pID; 
    Description = description; 
    Price = price; 


} 

public int getProductID() { 
    return this.ProductId; 

} 

public void setProductID(int input) { 
    this.ProductId = input; 
} 



public String getDescription() { 

    return this.Description; 
} 

public void setDescription(String DescriptionInput) { 
    this.Description = DescriptionInput; 
} 




public double getPrice() { 
    return this.Price; 
} 

public void setPrice(double priceInput) { 
    this.Price = priceInput; 
} 

public String toString(){ 
    return "Product Id: "+ this.ProductId + "Description: " + this.Description + " Price: " + this.Price; 
} 

}

最后,无论你怎么称呼它只是调用toString方法。

0

创建一个toString()方法,这样你就可以做到这一点System.out.println(Product);