我已经完成了这个程序,除非我将价格或数量对象设置为负数而未设置为0.方向说如果价格不是正数,则应设置为0.0,如果数量不是正数,应该设置为0.以下是我的代码可以告诉我哪里出错了。
本练习是3.12发票类表格Deitel第10版如何编程:
public class Invoice {
private String partNumber;
private String partDescription;
private int quantity;
private double priceperitem;
private double amount;
public Invoice(String number, String partDescription, int quantity, double price)
{
this.partNumber = number;
this.partDescription = partDescription;
this.quantity = quantity;
this.priceperitem = price;
}
public void setPartNumber(String number)
{
partNumber = number;
}
public String getPartNumber()
{
return partNumber;
}
public void setPartDescription (String description)
{
partDescription = description;
}
public String getPartDescription(){
return partDescription;
}
public void setQuantity(int count){
if(count > 0)
quantity = 0;
}
public int getQuantity(){
return quantity;
}
public void setPrice (double price){
if(price > 0.0)
priceperitem = price;
if(price < 0.0)
priceperitem = 0.0;
}
public double getPrice(){
return priceperitem;
}
public double getInvoiceAmount(){
amount = getQuantity() * getPrice();
return amount;
}
}
import java.util.Scanner;
public class InvoiceTest {
public static void main(String[] args) {
int quantity;
double price;
double invoiceAmount;
Invoice invoice1 = new Invoice("1234","Hammer",-5, -39.75);
Scanner keyboard = new Scanner (System.in);
System.out.printf( "Part number: %s\n", invoice1.getPartNumber());
System.out.printf( "Part Description: %s\n", invoice1.getPartDescription());
System.out.printf( "Quantity: %s\n", invoice1.getQuantity());
System.out.printf( "Price: %s\n", invoice1.getPrice());
}
}
答案 0 :(得分:1)
您正在检查条件,如果price<0
然后将价格设置为0,则使用setter方法,即方法setPrice
。但是你正在为价格建设者传递-ve论证,而这种建构者没有这样的检查。添加签入构造函数: -
public Invoice(String number, String partDescription, int quantity, double price)
{
this.partNumber = number;
this.partDescription = partDescription;
this.quantity = quantity;
if(price > 0.0)
priceperitem = price;
if(price < 0.0)
priceperitem = 0.0;
}
对于数量检查也是如此,在构造函数中以类似的方式添加数量检查。
另请注意,您在setQuantity中的条件无效,请将其更改为: -
if(quantity > 0)
this.quantity = price;
if(quantity < 0)
this.quantity = 0.0;
答案 1 :(得分:0)
setQuantity方法正在执行无效检查。将if(count &gt; 0)更改为if(count &lt; 0)。即使在此更改之后,它也不起作用,因为您根本不使用set方法。您可以在构造函数中初始化变量时执行此操作,
public Invoice(String number, String partDescription, int quantity, double price)
{
this.partNumber = number;
this.partDescription = partDescription;
**setQuantity(quantity);
setPrice(price);**
}