Question

In: Computer Science

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 getters and setters for the name and price. Try to be consistent with the behaviors of the setters compared to the constructor.

4. Write an equals method that returns true if two Item objects have the same name.

5. Write a toString method that returns the following String (replacing and with the fields of the object): “The item has a price of $.” Make sure the price is formatted to always round to two decimal places.

6. Study the code provided in the Inventory class. The addButton will add an Item to the ArrayList if that Item is new. This means the name of the Item must be different than any name already in the ArrayList.

7. In the Inventory class, you must implement the lambda expression for the addButton. Start by declaring a boolean to keep track of whether or not an item being added to the inventory (the ArrayList of Items) is actually new. This boolean is initialized to true.

8. Construct a new Item using the text from nameTextField for the name and the text from priceTextField for the price. If the constructor does not already handle the conversion, make sure the text for the price is converted to a double.

9. Write a for-each loop to iterate over the items in the ArrayList. Compare each item already in the ArrayList to the new item. If the name of any item in the ArrayList is the same as the name of the new item, set the boolean to false.

10. After the for-each loop completes, if the item is new, add the item to the ArrayList and display the following in the outputLabel: “Successfully added new item. The item has a price of $.” Keep in mind that the second sentence is the result of calling the object’s toString method. If the item is not new, display the following in the outputLabel: “Failed to add existing item.”

package inventory;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;

import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

import javafx.geometry.Insets;
import javafx.geometry.Pos;

import java.util.ArrayList;

public class Inventory extends Application
{ 
    public static void main(String[] args)
    {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage)
    {
        ArrayList itemsList = new ArrayList<>();
        
        Label nameLabel = new Label("Name: ");
        TextField nameTextField = new TextField();
        HBox nameHBox = new HBox(nameLabel, nameTextField);
        nameHBox.setAlignment(Pos.CENTER);
        nameHBox.setPadding(new Insets(10, 0, 0, 0));
        
        Label priceLabel = new Label("Price: ");
        TextField priceTextField = new TextField();
        HBox priceHBox = new HBox(priceLabel, priceTextField);
        priceHBox.setAlignment(Pos.CENTER);
        
        Button addButton = new Button("Add Item");
        Label outputLabel = new Label();
        
        addButton.setOnAction(event -> {
            // IMPLEMENT LAMBDA EXPRESSION FOR ADDBUTTON
        });
        
        VBox root = new VBox(10, nameHBox, priceHBox, addButton, outputLabel);
        root.setAlignment(Pos.TOP_CENTER);
        
        Scene scene = new Scene(root, 500, 500);
        
        primaryStage.setTitle("Inventory");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Make sure you copy below two classes into separate files as mentioned. Do not copy everything to a single file.


//Inventory.java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;

import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

import javafx.geometry.Insets;
import javafx.geometry.Pos;

import java.util.ArrayList;

public class Inventory extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        ArrayList itemsList = new ArrayList<>();

        Label nameLabel = new Label("Name: ");
        TextField nameTextField = new TextField();
        HBox nameHBox = new HBox(nameLabel, nameTextField);
        nameHBox.setAlignment(Pos.CENTER);
        nameHBox.setPadding(new Insets(10, 0, 0, 0));

        Label priceLabel = new Label("Price: ");
        TextField priceTextField = new TextField();
        HBox priceHBox = new HBox(priceLabel, priceTextField);
        priceHBox.setAlignment(Pos.CENTER);

        Button addButton = new Button("Add Item");
        Label outputLabel = new Label();

        addButton.setOnAction(event -> {
            boolean newItem = true; //initially assuming the item is new
            //creating an Item object using texts from name and price text fields
            Item item = new Item(nameTextField.getText(), priceTextField.getText());
            //looping through each item in itemsList
            for (Item it : itemsList) {
                //if current item equals new one, setting newItem to false and exiting loop
                if (it.equals(item)) {
                    newItem = false;
                    break;
                }
            }
            //if newItem is still true, adding to list and displaying success message on output label
            //else displaying an error message on output label.
            if(newItem){
                itemsList.add(item);
                outputLabel.setText("Successfully added new item. "+item);
            }else{
                outputLabel.setText("Failed to add existing item.");
            }
        });

        VBox root = new VBox(10, nameHBox, priceHBox, addButton, outputLabel);
        root.setAlignment(Pos.TOP_CENTER);

        Scene scene = new Scene(root, 500, 500);

        primaryStage.setTitle("Inventory");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

//Item.java

public class Item {
    //attributes
    private String name;
    private double price;

    //constructor taking text values for name and price
    public Item(String name, String priceTxt) {
        this.name = name;
        //parsing price from priceTxt
        this.price = Double.parseDouble(priceTxt);
    }
    
    //getters and setters

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public boolean equals(Object obj) {
        //returning true if obj is an item and it has the same name as this item
        return (obj instanceof Item) && ((Item) obj).getName().equalsIgnoreCase(this.getName());
    }

    public String toString() {
        //returns a string containing item name and price, formatted.
        return String.format("The item %s has a price of $%.2f", name, price);
    }

}

/*OUTPUT*/


Related Solutions

JAVAFX LAB 2 1. The Soda class has two fields: a String for the name and...
JAVAFX LAB 2 1. The Soda class has two fields: a String for the name and a double for the price. 2. The Soda class has two constructors. The first is a parameterized constructor that takes a String and a double to be assigned to the fields of the class. The second is a copy constructor that takes a Soda object and assigns the name and price of that object to the newly constructed Soda object. 3. The Soda class...
The GroceryItem class must maintain the name of the item and its price (a double). You...
The GroceryItem class must maintain the name of the item and its price (a double). You must read the grocery data from file, and store each line's information in a single GroceryItem object. In other words, there should be one GroceryItem object created for each line in the file. Implement all standard and necessary getters and setters, as well as constructors. Also, implement a calculateWithTax method that takes a double parameter, and returns the price with the tax added. The...
Base Class class TransportationLink { protected: string _name; double _distance; public: TransportationLink(const string &name, double distance);...
Base Class class TransportationLink { protected: string _name; double _distance; public: TransportationLink(const string &name, double distance); const string & getName() const; double getDistance() const; void setDistance(double); // Passes in the departure time (as minute) and returns arrival time (as minute) // For example: // 8 am will be passed in as 480 minutes (8 * 60) // 2:30 pm will be passed in as 870 minutes (14.5 * 60) virtual unsigned computeArrivalTime(unsigned minute) const = 0; }; #endif Derived Classes...
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...
Create a class named CollegeCourse that includes the following data fields: dept (String) - holds the...
Create a class named CollegeCourse that includes the following data fields: dept (String) - holds the department (for example, ENG) id (int) - the course number (for example, 101) credits (double) - the credits (for example, 3) price (double) - the fee for the course (for example, $360). All of the fields are required as arguments to the constructor, except for the fee, which is calculated at $120 per credit hour. Include a display() method that displays the course data....
Create a struct MenuItem containing fields for name (a string) and price (a float) of a...
Create a struct MenuItem containing fields for name (a string) and price (a float) of a menu item for a diner. Create a ReadItem() function that takes an istream and a MenuItem (both by reference) and prompts the user for the fields of the MenuItem, loading the values into the struct's fields. Create a PrintItem() function that takes an output stream (by reference) and a MenuItem (by value) and prints the MenuItem fields to the stream in a reasonable one-line...
Java... Design a Payroll class with the following fields: • name: a String containing the employee's...
Java... Design a Payroll class with the following fields: • name: a String containing the employee's name • idNumber: an int representing the employee's ID number • rate: a double containing the employee's hourly pay rate • hours: an int representing the number of hours this employee has worked The class should also have the following methods: • Constructor: takes the employee's name and ID number as arguments • Accessors: allow access to all of the fields of the Payroll...
Create a class named Horse that contains the following data fields: name - of type String...
Create a class named Horse that contains the following data fields: name - of type String color - of type String birthYear - of type int Include get and set methods for these fields. Next, create a subclass named RaceHorse, which contains an additional field, races (of type int), that holds the number of races in which the horse has competed and additional methods to get and set the new field. ------------------------------------ DemoHorses.java public class DemoHorses {     public static void...
Implement an Employee class that includes data fields to hold the Employee’s ID number, first name,...
Implement an Employee class that includes data fields to hold the Employee’s ID number, first name, last name, and hourly pay rate (use of string datatype is not allowed). Create an array of five Employee objects. Input the data in the employee array. Write a searchById() function, that ask the user to enter an employee id, if its present, your program should display the employee record, if it isn’t there, simply print the message ”Employee with this ID doesn’t exist”....
In Java, Here is a basic Name class. class Name { private String first; private String...
In Java, Here is a basic Name class. class Name { private String first; private String last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Name other) { return this.first.equals(other.first) && this.last.equals(other.last); } } Assume we have a program (in another file) that uses this class. As part of the program, we need to write a method with the following header: public static boolean exists(Name[] names, int numNames, Name name) The goal of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT