Question
Use exceptions to correct errors and please don't use stacks
2. Write a class called ShoppingBag to keep track of items purchased. The ShoppingBag contains a summary of an order. It will implement the Retail interface (given below) and will need some additional methods to place items in the bag and to output the bags current status. ShoppingBag contains the total cost of items purchased (before tax), the total after tax, the number of items in the bag, and the average cost ofan item. A. Create the following interface and use it when implementing the ShoppingBag class. a. public interface Retail total cost of all items before tax double RetailCost0; double AverageCost0; average cost of an item, before tax double TotalCost0; ll total cost of all items including tax ll number of items in the bag int Totalltems0; B. create a class called shoppingBag that implements the Retail interface. objects of this class represent a single shopping bag. Attributes of such an object include the number of items in the bag, the tax rate and the retail cost of those items. a. Create a constructor that accepts a tax rate as a double argument. b. Create a method called Buy that puts an item into the bag. accepts indicates argument indicating the quantity purchased and a double argument that five the of the item. For example, myBag.Buy(5, 10.50) represents buying items that cost 10.50 each.
media%2Fd45%2Fd453aa56-b045-4954-9458-12
0 0
Add a comment Improve this question Transcribed image text
Answer #1

/* JAVA Program to implement a shoppingbag application .
Prigram reads lines from a file and computes total number of items, total cost,
average cost, and use exception to count number of line contains invalid input
*/
import java.util.*;
import java.io.*;
//interface defined
interface Retail
{
   public double RetailCost();
   public double AverageCost();
   public double TotalCost();
   public int TotalItems();
}
//class defination
class ShoppingBag implements Retail
{
   private int noOfItems;
   private double taxRate;
   private double retailCost;
   //constructor to accept tax rate
   public ShoppingBag(double trate)
       {
           noOfItems=0;
           retailCost=0.00;
           taxRate=trate;
       }
//this method accepts number of items purchased ,and cost per item add it to the bag
   public void Buy(int n,double cost)
   {
       noOfItems+=n;
       retailCost=retailCost+(n*cost);
   }
//this method return retail cos\t
public double RetailCost()
   {
       return retailCost;
   }
//this method return average cost
public double AverageCost()
   {
   return (retailCost/noOfItems)   ;
   }
//this method return total cost after adding tax
public double TotalCost()
{
   double tax=retailCost*taxRate/100;
   return retailCost+tax;
}
//this method return number of items in bag
public int TotalItems()
   {
       return noOfItems;
   }
//retiurns a string containing output.
public String toString()
   {
   String s;
   s="Items :"+noOfItems+"\nRetail cost :$"+retailCost+"\nAverage item cost : $"+AverageCost();
   s+="\nTotal cost including tax("+taxRate+") : $"+TotalCost();
   return s;
   }

}

/////////////////////////////////////////
// main class
public class ShoppingBagApp
   {
       public static void main(String arg[]) throws FileNotFoundException
           {

           ShoppingBag bag=new ShoppingBag(7.00);
           int n,counterror=0;

           double cost;
           File file=new File("retail.txt");
           Scanner fin=new Scanner(file); // load file
           //read file until end
           while(fin.hasNext() )
               {
               try
                   {
                   if(fin.hasNextInt() || fin.hasNextDouble()) // check for valid input
                       {
                       n=fin.nextInt();
                       cost=fin.nextDouble();
                       bag.Buy(n,cost); //call to Buy()
                       }
                   else
                       {
                           throw new NumberFormatException();
                       }
                   }
           //catch block to count number of invalid input
           catch(NumberFormatException e)
                   {
                   counterror++;
                   fin.nextLine();
                   fin.nextLine();
                   }

               }
           System.out.println(bag);
           System.out.println("\n\nTherer were "+counterror + " lines of input skipped due to input mismatch exception");
       }
   }

------------------------------------------------------------------

//output

Add a comment
Know the answer?
Add Answer to:
Use exceptions to correct errors and please don't use stacks 2. Write a class called ShoppingBag...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help with my homework please. I should write this program in C++ language and...

    I need help with my homework please. I should write this program in C++ language and use Inventory.h file (header file), Inventory.cpp file (implementation file), and main.cpp file (main program). This is the program: Demonstrate the class in a driver program. Input validation, don’t accept negative values for item number, quantity, or cost. 6. Inventory Class Design an Inventory class that can hold information and calculate data for items ma retail store's inventory. The class should have the following private...

  • In a file named LLBag.java, write a class called LLBag that implements the Bag interface using...

    In a file named LLBag.java, write a class called LLBag that implements the Bag interface using a linked list instead of an array. You may use a linked list with or without a dummy head node. Bag interface code: /* * Bag.java * * Computer Science 112, Boston University */ /* * An interface for a Bag ADT. */ public interface Bag { /*    * adds the specified item to the Bag. Returns true on success    * and...

  • in java PART ONE ======================================= Below is the "RetailItem" class definition that we used in Chapter 6. Write a "CashRegister" class that leverages this "Ret...

    in java PART ONE ======================================= Below is the "RetailItem" class definition that we used in Chapter 6. Write a "CashRegister" class that leverages this "RetailItem" class which simulates the sale of a retail item. It should have a constructor that accepts a "RetailItem" object as an argument. The constructor should also accept an integer that represents the quantity of items being purchased. Your class should have these methods: getSubtotal: returns the subtotal of the sale, which is quantity times price....

  • Write a CashRegiste class that can be used with the Retntailtem class that you wrote in...

    Write a CashRegiste class that can be used with the Retntailtem class that you wrote in the module4. The cashRegister class should simulate the sale of a retail item. It should have a constructor that accepts a Retilltem objectject The constructor should also accept an integer that represents the quantity of item being purchased. In addition, the class should have the following properties and methods: as an argument. private final double TAX RATE private double retail; private int quantity; 0.06;...

  • Write code in Java programming language. The ShoppingCart class will be composed with an array of...

    Write code in Java programming language. The ShoppingCart class will be composed with an array of Item objects. You do not need to implement the Item class for this question, only use it. Item has a getPrice() method that returns a float and a one-argument constructor that takes a float that specifies the price. The ShoppingCart class should have: Constructors: A no-argument and a single argument that takes an array of Items. Fields: • Items: an array of Item objects...

  • I NEED HELP with this. please create a UML diagram. I need a simple code to...

    I NEED HELP with this. please create a UML diagram. I need a simple code to solve the problem.   The ADT Bag is a group of items, much like what you might have with a bag of groceries. In a software development cycle, specification, design, implementation, test/debug, and documentation are typical activities. The details are provided in the rest of the document. ADT Bag Specification: (Note: You should not change the names of the operations in your program. This should...

  • java Invoice class

    Create a class named Invoice that contains fields for an item number, name, quantity, price, and total cost. Create insurance methods that set the item name, quantity,and price. Whenever the price for quantity is set, recalculate the total (price times quantity). Also include a display Line() method that displays the item number,name, quantity, price, and total cost. Make sure you include a class named TestInvoice whose main method () declares three Invoice items. Create a method that prompts the user...

  • Use java and continue stage 2 and 3 stage 1 code public abstract class BabyItem { protected String name;...

    Use java and continue stage 2 and 3 stage 1 code public abstract class BabyItem { protected String name; public BabyItem() { name=""; } public BabyItem(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { } public abstract double getCost(); } ======================================================================================== public class BabyFood extends BabyItem { private int numberOfJars; private double pricePerDozen; public BabyFood() { super(); numberOfJars = 0; pricePerDozen = 0; } public BabyFood(int numberOfJars, double pricePerDozen) {...

  • Code should be in C# Create a class called SavingsAccount.  Use a static variable called annualInterestRate to...

    Code should be in C# Create a class called SavingsAccount.  Use a static variable called annualInterestRate to store the annual interest rate for all account holders.  Each object of the class contains a private instance variable savingsBalance, indicating the amount the saver currently has on deposit. Provide method CalculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by annualInterestRate divided by 12 – this interest should be added to savingsBalance.  Provide static method setAnnualInterestRate to set the annualInterestRate to a new value....

  • in python Write a class named RetaiI_Item that holds data about an item in a retail...

    in python Write a class named RetaiI_Item that holds data about an item in a retail store. The class should store the following data in attributes: • Item Number • Item Description • Units in Inventory • Price Create another class named Cash_Register that can be used with the Retail_Item class. The Cash_Register class should be able to internally keep a list of Retail_Item objects. The class should include the following methods: • A method named purchase_item that accepts a...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT