Yet Another Constructor Declairation and Instance Variable initialization - Java

Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four pieces of information as instance variables— a part number (type String), a part description (type String), a quantity of the item being pur- chased (type int) and a price per item (double). Your class should have a constructor that initializes the four instance variables. Provide a set and a get method for each instance variable. In addition, provide a method named getInvoiceAmount that calculates the invoice amount (i.e., multiplies thequantity by the price per item), then returns the amount as a double value. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0. Write a test application named InvoiceTest that demonstrates class Invoice’s capabilities.
  

Invoice Class


class invoice
{
    String partno, partdesc;
    int quantity;
    double price;
   
    double getInvoiceAmount()
    {
        double temp = getprice() * getquantity();
        if(temp<0)
        {
            temp = 0;
        }
        return temp;
    }
   
    invoice()
    {
    }
   
    invoice(String pn, String pd, int qty, double pri)
    {
        setpartno(pn);
        setpartdesc(pd);
        setquantity(qty);
        setprice(pri);      
    }
    void setpartno(String pn)
    {
        partno = pn;
    }
    void setpartdesc(String pd)
    {
        partdesc = pd;
    }
    void setquantity(int qty)
    {
        if(qty < 0)
        {
            qty = 0;
        }
        quantity = qty;
    }
    void setprice(double pri)
    {
        if(pri < 0)
        {
            price = 0;
        }
        price = pri;
    }
    String getpartno()
    {
        return partno;
    }
    String getpartdesc()
    {
        return partdesc;
    }
    int getquantity()
    {
        return quantity;
    }
    double getprice()
    {
        return price;
    }  
}

 

Test Program


import java.util.Scanner;

class thirdapp
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("\nEnter Part No. :: ");
        String pn = sc.nextLine();
        System.out.print("\nEnter Description :: ");
        String pd = sc.nextLine();
        System.out.print("\nEnter Quantity :: ");
        int qty = sc.nextInt();
        System.out.print("\nEnter Price/Item :: ");
        double pri = sc.nextDouble();
              
        invoice in = new invoice(pn, pd, qty, pri);
      
        double invoiceamount = in.getInvoiceAmount();
      
        System.out.print("\nTotal Invoice Amount :: "+invoiceamount);
              
    }
}



Post a Comment