Question

In: Computer Science

A constructor, with a String parameter representing the name of the item.

USE JAVA 

Item class

  • A constructor, with a String parameter representing the name of the item.

  • A name() method and a toString() method, both of which are identical and which return the name of the item.

BadAmountException Class

  • It must be a RuntimeException. A RuntimeException is a subclass of Exception which has the special property that we wouldn't need to declare it if we need to use it.

Inventory class

  • A constructor which takes a String parameter indicating the item type, an int parameter indicating the initial number of items in stock, and an int parameter indicating the limit to the number of items which can be purchased in any transaction. If we attempt to initialize the inventory with a negative number of items, the constructor should throw a BadAmountException with the message "Cannot keep a negative amount of items in stock".

  • A constructor which takes a String parameter indicating the item type, and an int parameter indicating the initial number of items in stock. This constructor assumes no purchase limit, so initialize the limit appropriately. If we attempt to initialize the inventory with a negative number of items, the constructor should throw a BadAmountException with the message "Cannot keep a negative amount of items in stock".

  • A getter and setter for the purchase limit, getLimit and setLimit.

  • A getter for the number of items currently in stock, getNum.

  • A getter for the type of item (i.e. the name of the item) in stock, getType.

  • A restock method which takes an int parameter and which doesn't return anything. This method restocks by adding the input amount to the current stock. If the input amount is negative, this method should throw a BadAmountException with the message "Cannot stock a negative amount of items".

  • A purchase method which takes an int parameter and which returns an array of Item. The input value represents a number of items to purchase. However, before a purchase can be made, several checks need to be done to make sure it is a legal transaction:If the transaction is valid, then we should purchase the specified number of items (updating the inventory accordingly), and return create and return an array of Item of the appropriate size and type (for example, if we request a purchase of two packages of "toilet paper", we would get back an array containing two Item objects whose name is "toilet paper").
    Note that since InventoryException is a checked exception, we may need to declare it to use it.

    1. If the input is negative, then the method should throw a BadAmountException with the message "Cannot purchase a negative amount of items".

    2. If the purchase amount is greater than the number of items in stock, then we should throw an InventoryException with the text "Not enough items in stock".

    3. If the purchase limit is zero, that means that there is a purchase freeze, so we should throw an InventoryException with the text "Purchasing freeze on item".

    4. If there is a limit but we've been requested to purchase more than the limit, we should throw a InventoryException with the text "Exceeded limit of LIMIT", where LIMIT is a number representing the purchase limit.

    5. Otherwise the transaction is valid.

The StoreSim class contains a single static method:

  • public static void sim(Inventory stock, int[] purchases).  If the purchase was successful, the method should output "purchased AMOUNT units ofITEMTYPE, REMAINNG remaining", for example, "purchased 50 units of toilet paper, 1 remaining". If an InventoryException is detected, then the method should print the exception's message and then continue as if nothing happened. If a BadAmountException is detected, then the method should print "(negative purchase AMOUNT ignored)" to the standard error stream instead of the standard output, and then continue as if nothing happened.

Solutions

Expert Solution


// Exception classes

// A BadAmountException class that will extend the parent class 'Exception' as mentioned in statement

import static java.lang.System.exit;

class BadAmountException extends Exception{

// A default constructor
public BadAmountException(){}

// A constructor which takes an error message as a parameter
// It can simply pass this error message up to the parent constructor.

public BadAmountException(String errorMessage) {
super(errorMessage);
}
}

// InventoryException

class InventoryException extends Exception{
// A default constructor
public InventoryException(){}

// A constructor which takes an error message as a parameter
// It can simply pass this error message up to the parent constructor.

public InventoryException(String errorMessage) {
super(errorMessage);
}
}

class Item{

// A string attribute which determines the name of the item

private String name;

// Constructor

public Item(String name) {
this.name = name;
}

// A name() method which would return the name of the item

public String name(){
return name;
}

// A toString() method identical to name() method

public String toString() {
return name;
}
}

class Inventory{

// A string variable determining name of item
String type;

// An integer determining number of items in stock
int num;

// An integer determining limit of number of items
int limit;

// Constructor initializing all above fields

public Inventory(String type, int num, int limit) {
this.type = type;

// If we attempt to initialize the inventory with a negative number of items
// A BadAmountException should be shown with the message "Cannot keep a negative amount of items in stock".

try{
if(this.num < 0) // If user passes negative
throw new BadAmountException("Cannot keep a negative amount of items in stock");
else
this.num = num;
}

// catch Exception if user enters negative number & show message to user

catch (BadAmountException e){
System.out.println(e.getMessage());
}

this.limit = limit;
}

// A getter and setter for the purchase limit, getLimit and setLimit


public void setLimit(int limit) {
this.limit = limit;
}

public int getLimit() {
return limit;
}

// A getter for the number of items currently in stock, getNum

public int getNum() {
return num;
}

// A getter for the type of item (i.e. the name of the item) in stock, getType.

public String getType() {
return type;
}

// A restock() method which takes an int parameter and which doesn't return anything

public void restock(int amount){

// It restocks by adding the input amount to the current stock
// If the input amount is negative, this method should throw a BadAmountException with the message "Cannot stock a negative amount of items".

// check if passed amount is negative or not

try {
if(amount < 0) // if amount is negative
throw new BadAmountException("Cannot stock a negative amount of items");
else // If not add it to current stock
num += amount;
}
catch (BadAmountException e){
System.out.println(e.getMessage());
}
}

// A purchase() method which takes an int parameter(number of items to purchase) and which returns an array of Item

public Item[] purchase(int noOfItemToPurchase){

// Lets make several that will make sure it is a legal transaction

//------------------------------------------------------------------------------------------------//
// If the input is negative
// then throw a BadAmountException with the message "Cannot purchase a negative amount of items"

try{
if(noOfItemToPurchase< 0) // If user passes negative, throw Exception
{
throw new BadAmountException("Cannot purchase a negative amount of items");
}
}
catch (BadAmountException e){
System.out.println(e.getMessage());
}

//------------------------------------------------------------------------------------------------//
// If the purchase amount is greater than the number of items in stock
// then throw an InventoryException with the text "Not enough items in stock"

try{
if(noOfItemToPurchase > num) // If that's case, throw Exception
{
throw new InventoryException("Not enough items in stock");
}
}
catch (InventoryException e){
System.out.println(e.getMessage());
}

//------------------------------------------------------------------------------------------------//
// If the purchase limit is zero, that means that there is a purchase freeze
// then throw an InventoryException with the text "Purchasing freeze on item"

try{
if(limit == 0){
throw new InventoryException("Purchasing freeze on item");
}
}
catch (InventoryException e){
System.out.println(e.getMessage());
}

//------------------------------------------------------------------------------------------------//
// If there is a limit but we've been requested to purchase more than the limit
// then throw a InventoryException with the text "Exceeded limit of LIMIT" where LIMIT is the purchase limit

try{
if(noOfItemToPurchase > limit){
throw new InventoryException("Exceeded limit of LIMIT");
}
}
catch (InventoryException e){
System.out.println(e.getMessage());
}

// If the user doesn't enter any wrong value (means there no exception occurs) --- it means transaction is valid
// so purchase the specified number of items (updating the inventory accordingly)
// and return an array of Item of the appropriate size and type

// Then just for returning array of item checking all above conditions for

if(!(noOfItemToPurchase <0 || noOfItemToPurchase > num || limit ==0 || noOfItemToPurchase > limit)){
Item[] arrayOfItems = new Item[noOfItemToPurchase];

for (int i=0; i

// Instantiating each Array object
arrayOfItems[i] = new Item(type);
}

// deducting items from inventory

num -= noOfItemToPurchase;

return arrayOfItems;
}
// else return null
else{
return null;
}
}
}

public class Driver {

public static void main(String[] args) {

// Driver code to test the code

// Creating an object of Inventory class

Inventory noodles = new Inventory("Hakka Noodles", 4, 28);

// For checking Exception , pass a negative value (Uncomment below line)

//noodles.restock(-7);

// Creating another object

Inventory toiletPaper = new Inventory("Toilet Paper", 10,50);

// Checking purchase() method, for exception uncomment below line

// toiletPaper.purchase(70);

Item[] items = toiletPaper.purchase(2);

// First checking if that any exception occurs check for null

if(!(items == null)){
for(int i=0; i System.out.println(items[i].name());
}
}
}
}

Sample output:

output with Exceptions (purchase(70)):

Output without exception


Related Solutions

Please write code in java and comment . thanks Item class A constructor, with a String...
Please write code in java and comment . thanks Item class A constructor, with a String parameter representing the name of the item. A name() method and a toString() method, both of which are identical and which return the name of the item. BadAmountException Class It must be a RuntimeException. A RuntimeException is a subclass of Exception which has the special property that we wouldn't need to declare it if we need to use it. It must have a default...
Create a class named BankAccount, containing: a constructor accepting a String corresponding to the name of...
Create a class named BankAccount, containing: a constructor accepting a String corresponding to the name of the account holder. a method, getBalance, that returns a double corresponding to the account balance. a method withdraw that accepts a double, and deducts the amount from the account balance. Write a class definition for a subclass, CheckingAccount, that contains: a boolean instance variable, overdraft. (Having overdraft for a checking account allows one to write checks larger than the current balance). a constructor that...
Implement function get_contact(contacts, name) that returns a string. The contacts and the name parameter are both...
Implement function get_contact(contacts, name) that returns a string. The contacts and the name parameter are both type string. This function checks for the name string in the contacts string and returns that person’s contact information. If the person is not found, the function returns, “name not in contact”. Assume input is always valid. Assume the same name is not repeated in contacts. [You may use split(), range(), len() ONLY and no other built-in function or method] Examples:               contacts = “Frank...
Implement function get_contact(contacts, name) that returns a string. The contacts and the name parameter are both...
Implement function get_contact(contacts, name) that returns a string. The contacts and the name parameter are both type string. This function checks for the name string in the contacts string and returns that person’s contact information. If the person is not found, the function returns, “name not in contact”. Assume input is always valid. Assume the same name is not repeated in contacts. [You may use split(), range(), len() ONLY and no other built-in function or method] Examples:               contacts = “Frank...
Write a function called fnReadInParameters() that takes as parameter(s): • a string indicating the name of...
Write a function called fnReadInParameters() that takes as parameter(s): • a string indicating the name of the parameter le This function should return a dictionary that stores all of the parameter le data of the SIR model in a format that we will describe further below.
1. The Item class includes two fields: a String for the name and a double for the price of an item that will be added to the inventory.
  1. The Item class includes two fields: a String for the name and a double for the price of an item that will be added to the inventory. 2. The Item class will require one constructor that takes a name and price to initialize the fields. Since the name and price will be provided through TextFields, the parameters can be two Strings (be sure to convert the price to a double before storing this into the field). 3. Write...
JAVA The class will have a constructor BMI(String name, double height, double weight). The class should...
JAVA The class will have a constructor BMI(String name, double height, double weight). The class should have a public instance method, getBMI() that returns a double reflecting the person's BMI (Body Mass Index = weight (kg) / height2 (m2) ). The class should have a public toString() method that returns a String like Fred is 1.9m tall and is 87.0Kg and has a BMI of 24.099722991689752Kg/m^2 (just print the doubles without special formatting). Implement this class (if you wish you...
4. Implement the function read_info_file that consumes a file name (string) as its parameter and returns...
4. Implement the function read_info_file that consumes a file name (string) as its parameter and returns a list of strings - one element for each line in the file. These lines should have all the whitespace removed from both ends of the line. a. See the formatting of the individual_info data file. Consider how a file can be read into the program. In Python language
The Person Class Uses encapsulation Attributes private String name private Address address Constructors one constructor with...
The Person Class Uses encapsulation Attributes private String name private Address address Constructors one constructor with no input parameters since it doesn't receive any input values, you need to use the default values below: name - "John Doe" address - use the default constructor of Address one constructor with all (two) parameters one input parameter for each attribute Methods public String toString() returns this object as a String, i.e., make each attribute a String, concatenate all strings and return as...
1. From the constructor, you infer that the name of the class containing the constructor must be_______ .
1. From the constructor, you infer that the name of the class containing the constructor must be_______ .2. Fill in the blanks so that the statement will instantiate a JButton object and assigns it to variable of JButton type:JButton btn= _______ ("OK");3. Fill in the blanks to complete the description of the constructor in the corresponding UML class diagram:+<>______( _____ : ______)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT