I have pretty much completed this program except when I set a price or quantity object to a negative number it does not set to 0. The directions say if the price is not a positive number it should be set to 0.0 and if the quantity is not a positive number it should be set to 0. Here are my codes can anyone tell me where I went wrong.
This exercise is 3.12 Invoice class form Deitel 10th edition How to program:
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());
}
}
You are checking for the condition if price<0
then set price to 0 , in you setter method , i.e in method setPrice
. But you are passing -ve argument for price thorugh constructor, which has no such check. Add the check in constructor too:-
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;
}
Same goes for Quantity check, add check for quantity in constructor in similar way.
Also note that your condition in setQuantity is not valid change it to:-
if(quantity > 0)
this.quantity = price;
if(quantity < 0)
this.quantity = 0.0;