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...
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...
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 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...
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...
A constructor, with a String parameter representing the name of the item.
USE JAVA Item classA 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 ClassIt 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 classA constructor which takes a String parameter indicating the item type, an int parameter indicating the initial...
with PHP Create a class called Employee that includes three instance variables—a first name (type String),...
with PHP Create a class called Employee that includes three instance variables—a first name (type String), a last name (type String) and a monthly salary int). Provide a constructor that initializes the three instance data member. Provide a set and a get method for each instance variable. If the monthly salary is not positive, do not set its 0. Write a test app named EmployeeTest that demonstrates class Employee’s capabilities. Create two Employee objects and display each object’s yearly salary....
QUESTION 60 Given the following Product structure: struct Product {     string name;     double price;...
QUESTION 60 Given the following Product structure: struct Product {     string name;     double price;     int quantity;     bool equals(const Product&); }; how would you define the equals function so two products are equal if their names and prices are equal? a. bool equals(const Product& to_compare) {     return (name == to_compare.name && price == to_compare.price); } b. bool Product::equals(const Product& to_compare) {     return (name == to_compare.name || price == to_compare.price); } c. bool equals(const Product& to_compare)...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT