Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

solve two parts Lab 4.1 Starting with a new NetBeans Java application (project)

ID: 3884621 • Letter: S

Question

solve two parts

Lab 4.1

Starting with a new NetBeans Java application (project) named CPS151_Lab4, add a CashRegister class that models a store cash register (see the demo on How to define a Java class in NetBeans). Make sure your new class is in the same package as the main class.

Then, add to this class:

instance variable for the list of item prices,

constructor that creates the list of item prices (initially empty),

instance methods to:

add an item with a given price (argument),

get the purchase total,

get the number of items purchased,

clear the case register for the next customer,

return (as a String) the list of item prices.

Lab 4.2

Switch back to the CPS151_Lab4 class and add code to the main method that does the following:

Declare/create an object of type CashRegister.

Using method calls to the CashRegister object, add three items with prices $1.95, $0.95 and $2.50.

Using method calls to the CashRegister object, display (1) the number of items purchased (2) the list of prices, and (3) the total price of the entire purchase.

Explanation / Answer

import java.io.*;
import java.util.*;

class CashRegister {

    private ArrayList<Double> list;
    private double purchaseTotal;
    public CashRegister(){
         list = new ArrayList<Double>();
         purchaseTotal = 0;
    }
    public void clear(){
       list.clear();
    }
    public void add(double a){
        list.add(a);
        purchaseTotal = purchaseTotal + a;
    }
    public double getPurchaseTotal(){
        return purchaseTotal;
    }
    public int getNumberOfItems(){
        return list.size();
    }
    public String toString(){
       String str = "";
       for (int i = 0; i<list.size(); i++){
           str = str + " $" + String.valueOf(list.get(i));
       }
       return str;
    }
}


public class DemoCashRegister {
    public static void main(String[] args){
         CashRegister ct = new CashRegister();
         ct.add(1.95);
         ct.add(0.95);
         ct.add(2.50);
         System.out.println(ct.toString());
         System.out.println("Number of items: " + ct.getNumberOfItems());
         System.out.println("Purchase Total: " + ct.getPurchaseTotal());
        

    }
}