Reading the code there are some flaws in your logic, lets start at the top and go through it.
It is an accepted convention in Java that all class names start with a capital letter and all other identifiers with a lower case letter.
So, with our class name
Order
, let's look at the variables. A
static
variable is shared by all instances of the class, so whenever you reference
OrderNum
it is the same value as used by every other class. The normal approach for this is to have a static last number and an instance variable with the current value for the object; I'll demonstrate this in a while.
It is also considered best practice to have no public member variables, keep them private and expose accessor methods.
So our class now [without any methods] becomes:
public class Order {
private static int lastOrderNum = 0;
private int orderNumber;
private double price;
private double discount;
private int quantity;
private double total;
private String productName;
private String message;
private boolean isDisCounted;
private boolean isValidOrder;
}
Note nothing is initialised bar the static last order number.
Now a good approach, that I would recommend to you, is to have a single constructor that does the work and all the other constructors call into it:
public Order()
{
Order("",0.0,0);
}
public Order(String s, double d, int i)
{
Order("",0.0,0,0.0);
}
public Order(String productName, double price, int quantity, double discount)
{
this.orderNumber = ++Order.lastOrderNumber;
this.productName = productName;
this.price = price;
this.quantity = quantity;
this.discount = discount;
this.calculate();
}
Now we have a simple constructor that anyone can understand, better for maintainablility.
Now for the calculate method. Check it's parameter and if they're all okay work out the total:
public void calculate()
{
if (this.productName == null || "".equals(this.productName))
{
this.message = "ERROR: No product name supplied";
}
else if (this.price <= 0.0)
{
this.message = "ERROR: Price must be positive.";
}
else if (this.quantity <= 0.0)
{
this.message = "ERROR: Quantity must be positive.";
}
else if (this.discount <= 0.0 || this.discount >= 100.0)
{
this.message = "ERROR: Discount must be between 0 and 100.";
}
else
{
this.message = null;
this.total = this.quantity * this.price;
if (this.discount > 0.0) {
this.total = this.total * (100.0 - this.discount) / 100.0;
}
}
}
The final method,
toString
should return the CURRENT state of the object, without changing anything. Once a return statement is reached, the method exits:
public String toString()
{
if (this.message != null) {
return this.message ;
}
if (this.discount = 0.0)
{
return "order number"+"\n" + this.orderNum+"\n"+"\n"+
"price"+this.price+"\n"+
"quantity"+this.quantity+"\n"+
"total"+this.total;
}
return "order number"+"\n" + this.orderNum+"\n"+"\n"+
"price"+this.price+"\n"+
"quantity"+this.quantity+"\n"+
"discount"+this.discount+"\n"+
"total"+this.total;
}
Simples.