我正在尝试编写一个非常简单的程序,为购买的商品生成发票。
我有一个带有setter和getter的驱动程序类,以及一个应该调用它们的对象类。但是,当我打印出发票时,它只会对所有内容产生空响应。

这是我的驱动程序类:

public class Invoice {

private String partNumber;  //part number of item
private String description; //description of item
private int quantity;       //quantity being purchased
private double itemPrice;   //price of item

//constructor
public Invoice(String partNumber, String description, int quantity, double itemPrice) {
    partNumber = partNumber;
    description = description;
    if (quantity < 0) {
        quantity = 0;
    }
    if (itemPrice < 0.0) {
        itemPrice = 0.0;
    }
}

public void setPartNumber(String number) {
    partNumber = number; //store the partNumber
}

public void setDescription(String description) {
    description = description;//store the description
}

public void setQuantity(int quantity) {
    quantity = quantity;//store the quantity
}

public void setItemPrice(double price) {
    itemPrice = price;//store the itemPrice
}

public String getPartNumber() {
    return partNumber;//retrieve the partNumber
}

public String getDescription() {
    return description;//retrieve the description
}

public int getQuantity() {
    return quantity;//retrieve the quantity
}

public double getItemPrice() {
    return itemPrice;//retrieve the itemPrice
}

//get price for item purchased.
public double getInvoiceAmount(double amount) {
    amount = itemPrice * quantity;
    if (amount < 0) {
        amount = 0.0;
    }
    return amount;
}
}


这是我的对象类:

public class InvoiceTest {

public static void main(String[] args) {
    Invoice invoice1 = new Invoice ("0001", "Hammer: used to hit nails.", 1, 10.0);

    System.out.println("Item purchased: " + invoice1.getPartNumber() +
            "\n Description: " + invoice1.getDescription() +
            "\n Amount:" + invoice1.getQuantity() +
            "\n price: " + invoice1.getQuantity());
    System.out.println();
    System.out.println("Total price: " + invoice1.getInvoiceAmount(amount));
}

}

最佳答案

您忘记了将变量分配给构造函数中的字段。使用this关键字来引用类字段:

public Invoice(String partNumber, String description, int quantity, double itemPrice) {
    //here's an example
    //partNumber = partNumber
    this.partNumber = partNumber;
    //description = description;
    this.description = description;
    //similar for other assignments inside the constructor...
}


您还必须在设置者中执行此操作:

public void setPartNumber(String partNumber) {
    this.partNumber = partNumber; //store the partNumber
}

09-15 23:28