VERY new to Java, so I am feeling like a child right now. The joys of learning a new language I guess.
Here is my Invoice Class:
public class Invoice {
//member inits
private int numberOfInvoices = 0;
private String companyName;
private double amountDue;
private String chargeDate;
private static int invoiceNumber = 0;
//constructor
public Invoice(String _companyName, double _amountDue, String _chargeDate)
{
numberOfInvoices++;
companyName = _companyName;
amountDue = _amountDue;
chargeDate = _chargeDate;
invoiceNumber = numberOfInvoices;
}
//getters
public String getCompanyName()
{
return companyName;
}
public double getAmountDue()
{
return amountDue;
}
public String getChargeDate()
{
return chargeDate;
}
public int getInvoiceNumber()
{
invoiceNumber = numberOfInvoices + 1;
return invoiceNumber;
}
//setters
public void setCompanyName(String _companyName)
{
companyName = _companyName;
}
public void setAmountDue(double _amountDue)
{
amountDue = _amountDue;
}
public void setChargeDate(String _chargeDate)
{
chargeDate = _chargeDate;
}
//helpers
public int incrementInvoices()
{
return numberOfInvoices++;
}
}
And here is the main method where I am trying to create three of these invoices, but increment the invoice number each time a new one is created.
public class InvoiceCreator {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Invoice invoice1 = new Invoice("Amazing Software", 5000.00, "January 18, 2009");
System.out.println(invoice1);
Invoice invoice2 = new Invoice("Best Programs", 4000.00, "February 18, 2009");
System.out.println(invoice2);
Invoice invoice3 = new Invoice("Champion Code", 3000.00, "March 18, 2009");
System.out.println(invoice3);
}
}
I'm also new to the IDE (netbeans), but through debugging and looking at each of the classes I created, all the fields are being initialized correctly, but the invoiceNumber = 1 on every one of them.
What am I doing incorrectly here?
You need to use a static field to generate incremental invoice numbers, not store the individual invoice numbers.
Try this:
public class Invoice {
//member inits
private static int nextInvoiceNumber = 0;
private String companyName;
private double amountDue;
private String chargeDate;
private int invoiceNumber = 0;
//constructor
public Invoice(String _companyName, double _amountDue, String _chargeDate)
{
invoiceNumber = nextInvoiceNumber;
nextInvoiceNumber++;
companyName = _companyName;
amountDue = _amountDue;
chargeDate = _chargeDate;
}
....
Declare numberOfInvoices to be static
, so that there is a single value for the entire class, rather than a separate value for each instance.
private static int numberOfInvoices = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With