Question

In: Computer Science

In Java The Order class should have:  Seven instance variables: the order number (an int),...

In Java

The Order class should have:  Seven instance variables: the order number (an int), the Customer who made the order, the Restaurant that receives the order, the FoodApp through which the order was placed, a list of food items ordered (stored as an array of FoodItem), the total number of items ordered (an int), and the total price of the order (a double).  A class constant to set the maximum number of items that can be ordered (an int). Set it to 10.  A constructor that accepts three parameters, the Customer, the Restaurant and the FoodApp, and initializes the corresponding instances variables. The array of FoodItems will be a partially filled array. It should be initialized according to the maximum number of items that can be ordered, and be empty at the beginning. The total number of items ordered should be initialized accordingly. The total price shall be initialized to 0. The order number shall have 6 digits, and start with a 9. Every order should have a distinct order number, starting from 900001, then 900002, then 900003 and so on. You will need to add either an instance variable or a class variable to accomplish this (choose wisely).  An addToOrder(FoodItem) method that adds the FoodItem received as a parameter to the FoodItem array, only if it is available (i.e. not sold out) and if there is space left in the array. If the FoodItem was added, the method returns true (it returns false otherwise). You can assume that the FoodItem belongs to the restaurant’s menu (no need to check if it’s on the menu). Don’t forget to update here: the amount in stock for the FoodItem (decrement by 1), the total price of the order, and the total number of items ordered.  A toString method that returns a String containing the FoodApp name, the order #, the customer name, the Restaurant name, the list of items ordered and the total price (formatting it exactly as shown in the example below). You will need to add some accessors in the previous classes (aka get methods) to get only the name of the Customer, FoodApp and Restaurant, instead of the full String representation of those.

=============================================

public class FoodItem {

    /*Four instance variables: a name (a String), a cost (a double), a selling price (a double), and the number of

items available in stock for selling (an int)*/

    String name;

    double cost;

    double price;

     int   numberOfItem;

/* A constructor that takes four parameters, in the above order, which are used to initialize the four instance

variables.*/

    public FoodItem(String name, double cost, double price, int numberOfItem){

        this.name = name;

        this.cost = cost;

        this.price = price;

        this.numberOfItem = numberOfItem;

    }

/* A method isAvailable that checks if there are items available for selling (returns false is no items are available,

true otherwise)*/

    public boolean isAvailable(int numberOfItem){

        if ( numberOfItem <= 0)

            return false;

        else

            return true;

        

    }

/* A toString method which returns a String containing the name of the food item and the selling price. If the

item is not available, add “(SOLD OUT)” next to the price, making use of the isAvailable method. Follow the

format shown in the example output below.*/

    @Override

    public String toString(){

        String update ="";

        if ( this.numberOfItem <= 0)

            update =" (SOLD OUT)";

        return"- "+this.name +"\n$ "+ this.price + update;

    }

// A method setSellingPrice that takes a new price as a parameter, and updates the selling price instance variable.

    public void setSellingPrice( double TheSellingPrice){  

        price = TheSellingPrice;

    }

// A method decrementStock that decrements the number of items in stock by 1.

    public int decrementStock(int x){

        return numberOfItem -= x;

    }

// A method increaseStock that takes an amount of additional stock as a parameter, and adds it to the existing stock available for selling. */

    public int increaseStock(int x){

        return numberOfItem += x;

    }

}//FoodItem

Solutions

Expert Solution

file-name :   FoodItem.java
--------------------------------------------
this code is provided by you in the question itself, but I made one small change in this code ( indicated in red-bold color )
----------------------------------------------------------------------------------------------------
public class FoodItem {
    /*Four instance variables: a name (a String), a cost (a double), a selling price (a double), and the number of
items available in stock for selling (an int)*/
    String name;
    double cost;
    double price;
    int numberOfItem;

/* A constructor that takes four parameters, in the above order, which are used to initialize the four instance
variables.*/
    public FoodItem(String name, double cost, double price, int numberOfItem)  {
        this.name = name;
        this.cost = cost;
        this.price = price;
        this.numberOfItem = numberOfItem;
    }

/* A method isAvailable that checks if there are items available for selling (returns false is no items are available,
true otherwise)*/

    // I think, here we should not pass any parameter.
    // because it checks the item is available or not based on numberOfItem member. So we should not pass it as parameter.
    public boolean isAvailable() {
        if ( this.numberOfItem <= 0)
            return false;
        else
            return true;
    }

/* A toString method which returns a String containing the name of the food item and the selling price. If the
item is not available, add “(SOLD OUT)” next to the price, making use of the isAvailable method. Follow the
format shown in the example output below.*/
    @Override
    public String toString(){
        String update ="";
        if ( this.numberOfItem <= 0)
            update =" (SOLD OUT)";
        return"- "+this.name +"\n$ "+ this.price + update;
    }

// A method setSellingPrice that takes a new price as a parameter, and updates the selling price instance variable.
    public void setSellingPrice( double TheSellingPrice){
        price = TheSellingPrice;
    }

// A method decrementStock that decrements the number of items in stock by 1.

    public int decrementStock(int x){
        return numberOfItem -= x;
    }

// A method increaseStock that takes an amount of additional stock as a parameter, and adds it to the existing stock available for selling. */
    public int increaseStock(int x){
        return numberOfItem += x;
    }

}//FoodItem

========================================================================================================================

file-name: Order.java
----------------------------------------
import java.util.Arrays;
public class Order {
    // instance variables
    int orderNumber;
    String customerName;
    String restaurantName;
    String appName;
    FoodItem[] foodItem;
    int numOfItemsOrdered;
    double price;

    // order number should be unique for each order.
    static int currentOrderNumber = 900000;
    // maximum number of items that can be ordered
    final int maxOrders = 10;

    //constructors
    Order ( String name, String placeName, String appName) {
        this.customerName = name;
        this.restaurantName = placeName;
        this.appName = appName;
        foodItem = new FoodItem[maxOrders];
        this.price = 0;
        this.numOfItemsOrdered = 0;
        this.orderNumber = ++currentOrderNumber;
    } // END of constructor.

    public String getRestaurantName() {
        return restaurantName;
    }
    public String getAppName() {
        return appName;
    }
    public String getCustomerName() {
        return customerName;
    }
    public int getOrderNumber() {
        return orderNumber;
    }
    public double getPrice() {
        return price;
    }

    public FoodItem[] getFoodItem() {
        return foodItem;
    }

    /**
     * takes item name as input and checks whether the number of orders crosses MAX_ORDERS or not.
     * if not then adds into the array.
     * Every time an item is added into array ( i.e.. order successfully placed , stock of the item should be decremented by 1)
     * @param item
     * @return true , if added to the foodItem array
     * else returns false
     */
    public  boolean addToOrder(FoodItem item) {
        if(this.numOfItemsOrdered  < 10 && item.isAvailable()) {
            this.foodItem[numOfItemsOrdered] = item;
            this.numOfItemsOrdered++;
            this.price = this.price + item.price;
            item.decrementStock(1);
            return true;
        }
        return false;
    }

    public String toString() {

        // helps in printing the food items:
        StringBuffer sb = new StringBuffer();
        FoodItem[] temp = getFoodItem();
        for(FoodItem each: temp) {
            if(each != null) {
                sb.append(each.name);
                sb.append(" | ");
            }
        }
        String  str = "Food App Name: "+getAppName() +
                "\nOrder number: "+getOrderNumber() +
                "\ncustomer Name: "+getCustomerName() +
                "\nrestaurant name: " + getRestaurantName()+
                "\nItems Ordered: " + sb +
                "\n Total price: " +getPrice();

        return str;

    }
}

=====================================================================================

file name: Main.java
---------------------------------------
NOTE : I Have implemented this Main class, just to show the functionality of Order and FoodItem class, 
I am not taking any user input here. I declared Objects to show you how it works.

you can use Scanner class to read inputs from user ( like which food item to add )and intialise the object with constructor. It is easy to do that.
----------------------------------------------------------------------------------------------------------
public class Main {
    public static void main(String[] args) {

        //Creating some FoodItem objects
        FoodItem f1 = new FoodItem("Biryani",50,75,7);
        FoodItem f2 = new FoodItem("Dosa",10,15,1);
        FoodItem f3 = new FoodItem("Pizza",25,30,6);


        // Now here I am demonstrating how Orders work.
        Order o1 = new Order("Rahul", "Mc Donald's", "Swiggy");
        o1.addToOrder(f1);
        o1.addToOrder(f2);

        // see here, f2 is not there in stock and now I am calling addToOrder method, so it returns false.
        if(o1.addToOrder(f2))
        {
            System.out.println(" item ordered successfully");
        }
        else {
            System.out.println(" Cannot add now, already reached max order limit");
        }
        System.out.println(o1);

        System.out.println("**********************");

        Order o2 = new Order("kiran","BAWARCHI","zomato");
        o2.addToOrder(f1);
        o2.addToOrder(f3);

        System.out.println(o2);
    }
}

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

OUTPUT:

THANK YOU !! If you have doubts ask in comments , I will add that in the answer. Please UPVOTE if you like my effort.


Related Solutions

(java) Write a class called CoinFlip. The class should have two instance variables: an int named...
(java) Write a class called CoinFlip. The class should have two instance variables: an int named coin and an object of the class Random called r. Coin will have a value of 0 or 1 (corresponding to heads or tails respectively). The constructor should take a single parameter, an int that indicates whether the coin is currently heads (0) or tails (1). There is no need to error check the input. The constructor should initialize the coin instance variable to...
SalaryCalculator in Java. The SalaryCalculator class should have instance variables of: an employee's name, reportID that...
SalaryCalculator in Java. The SalaryCalculator class should have instance variables of: an employee's name, reportID that is unique and increments by 10, and an hourly wage. There should also be some constructors and mutators, and accessor methods.
(a) Create a Card class that represents a playing card. It should have an int instance...
(a) Create a Card class that represents a playing card. It should have an int instance variable named rank and a char variable named suit. Include the following methods: A constructor with two arguments for initializing the two instance variables. A copy constructor. A method equals — with one argument — which compares the calling object with another Card and returns true if and only if the corresponding ranks and suits are equal. Make sure your method will not generate...
You need to make an AngryBear class.(In java) The AngryBear class must have 2 instance variables....
You need to make an AngryBear class.(In java) The AngryBear class must have 2 instance variables. The first instance variable will store the days the bear has been awake. The second instance variable will store the number of teeth for the bear. The AngryBear class will have 1 constructor that takes in values for days awake and number of teeth. The AngryBear class will have one method isAngry(); An AngryBear is angry if it has been awake for more than...
JAVA Write a Temperature class that has two instance variables: a temperature value (a floating-point number)...
JAVA Write a Temperature class that has two instance variables: a temperature value (a floating-point number) and a character for the scale, either C for Celsius or F for Fahrenheit. The class should have four constructor methods: one for each instance variable (assume zero degrees if no value is specified and Celsius if no scale is specified), one with two parameters for the two instance variables, and a no-argument constructor (set to zero degrees Celsius). Include the following: (1) two...
#Write a class called "Burrito". A Burrito should have the #following attributes (instance variables): # #...
#Write a class called "Burrito". A Burrito should have the #following attributes (instance variables): # # - meat # - to_go # - rice # - beans # - extra_meat (default: False) # - guacamole (default: False) # - cheese (default: False) # - pico (default: False) # - corn (default: False) # #The constructor should let any of these attributes be #changed when the object is instantiated. The attributes #with a default value should be optional. Both positional #and...
This is python #Create a class called Rectangle. Rectangle should #have two attributes (instance variables): length...
This is python #Create a class called Rectangle. Rectangle should #have two attributes (instance variables): length and #width. Make sure the variable names match those words. #Both will be floats. # #Rectangle should have a constructor with two required #parameters, one for each of those attributes (length and #width, in that order). # #Rectangle should also have a method called #find_perimeter. find_perimeter should calculate the #perimeter of the rectangle based on the current values for #length and width. # #perimeter...
Java Implement a class MyInteger that contains: • An int data field/instance variable named value that...
Java Implement a class MyInteger that contains: • An int data field/instance variable named value that stores the int value represented by this object. • A constructor that creates a MyInteger object for a default int value. What default value did you choose? What other values did you consider? Why did you make this choice? • A constructor that creates a MyInteger object for a specified int value. • A getter method, valueOf(), that returns value. • A setter method,...
Purpose: To write an Object-Oriented application that creates a Java class with several instance variables, a...
Purpose: To write an Object-Oriented application that creates a Java class with several instance variables, a constructor to initialize the instance variables, several methods to access and update the instance variables’ values, along with other methods to perform calculations. Also, write a test class that instantiates the first class and tests the class’s constructor and methods. Details: Create a class called Rectangle containing the following: Two instance variables, An instance variable of type double used to hold the rectangle’s width....
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name...
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name (type String), a last name (type String) and a monthly salary (double). Provide a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, do not set its value. Write a test app names EmployeeTest that demonstrates class EMLOYEE’s capabilities. Create two EMPLOYEE objects and display each object’s yearly...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT