Question

In: Computer Science

Please write code in java and comment . thanksItem classA 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 constructor.

  • It must have a constructor which takes an error message as a parameter. It can simply pass this error message up to the parent constructor.

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.

Solutions

Expert Solution

Program code to copy:


// 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 any 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...
Code in Java Write a recursive method, reverseString, that accepts a String and returns the String...
Code in Java Write a recursive method, reverseString, that accepts a String and returns the String reversed. Write a recursive method, reverseArrayList, that accepts an ArrayList of Strings and returns the ArrayList in reserve order in reserve order of the input ArrayList. Write a main method that asks the user for a series of Strings, until the user enters “Done” and puts them in an ArrayList. Main should make use to reverseArrayList and reverseString to reverse each String in the...
Convert the following UML diagram into the Java code. Write constructor, mutator and accessor methods for...
Convert the following UML diagram into the Java code. Write constructor, mutator and accessor methods for the given class. Create an instance of the class in a main method using a Practice class. Note: The structure of the class can be compiled and tested without having bodies for the methods. Just be sure to put in dummy return values for methods that have a return type other than void.      
Write this code in java and don't forget to comment every step. Write a method which...
Write this code in java and don't forget to comment every step. Write a method which asks a baker how hot their water is, and prints out whether it is OK to make bread with the water. If the water is at or above 110F, your method should print "Too Warm." If the water is below 90.5F, print "Too Cold." If it is in between, print "Just right to bake!" For example, if the user inputs the number 100.5, the...
Write Java code that prompts the user for a string and tells them if the grouping characters in that string are balanced.
Write Java code that prompts the user for a string and tells them if the grouping characters in that string are balanced. Grouping characters are ( and ), [ and ], and { and }. I got the basic idea for this problem from HackerRank. It’s also a very common interview question.*******************8Example output**************Enter the expression:{[()]} {[()]}is balancedEnter the expression: {()()} {()()}is balancedEnter the expression: {([[])} {([[])}is not balancedEnter the expression: {([)]} {([)]}is not balanced
This question is about java program. Please show the output and the detail code and comment...
This question is about java program. Please show the output and the detail code and comment of the each question and each Class and interface. And the output (the test mthod )must be all the true! Thank you! Question1 Create a class Animal with the following UML specification: +-----------------------+ | Animal | +-----------------------+ | - name: String | +-----------------------+ | + Animal(String name) | | + getName(): String | | + getLegs(): int | | + canFly(): boolean | |...
Write a java code segment to declare an array of size 10 of type String and...
Write a java code segment to declare an array of size 10 of type String and read data for them from a file, prompt user for the file name. Data is stored in a file with 1 string per line.
Write the following program in java please. a. Include a good comment when you write the...
Write the following program in java please. a. Include a good comment when you write the method described below: Method method1 receives an integer, n, and a real number, d, and returns a real number. If the integer is positive it returns the square root of the real number added to the integer. If the integer is negative or zero it returns the absolute value of the integer multiplied by the real number. b. Write the statements from the main...
Parse string java code Write a recursive program that can calculate the value of a given...
Parse string java code Write a recursive program that can calculate the value of a given polynomial in a string, which is not more than the tenth order, for the given x. The polynomial will be given in the following format and should display the value of the polynomial for spaced-out x Using index of for -/+
Please write the code JAVA Write a program that allows the user to enter the last...
Please write the code JAVA Write a program that allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate. The program should then output each candidate’s name, the number of votes received, and the percentage of the total votes received by the candidate. Your program should also output the winner of the election. A sample output is: Candidate      Votes Received                                % of Total Votes...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT