Question

In: Computer Science

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 input file, input.txt is attached to this assignment. You can assume each item has only one name without space (i.e., beef, pork, chicken, salad are all acceptable, but roast beef, roast chicken, honey ham, kale salad are not.)

Store all the objects of type GroceryItem in an ArrayList, and then in the main file, write a method that takes the ArrayList as a parameter, and prints out all the items with their pre- and post-tax prices.

The file I/O should take place in the GroceryItemDemo class, NOT the GroceryItem class.

**input.txt is as follows**

Tomatoes 1.99
Fudge 2.99
Bananas 1.99
Popcorn 0.99
Jerky 3.99
Milk 1.99

Two separate class files are required. We are using Netbeans with javaFX. I have input.txt in the correct place Im just confused on how to execute this.

Solutions

Expert Solution

Thanks for the question, here are the two classes you will be needing.

Please do update the inputFileName when you run the program in your system. Comments are included so that you can follow the code.

Let me know for any questions/doubts or incase you need any help.

thanks a lot !

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

public class GroceryItem {

    private String name;
    private double price;

    public GroceryItem(String name, double price) {
        this.name = name;
        this.price = price;
    }

    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;
    }

    @Override
    public String toString() {
        return "Name: " + getName() + ", Price $" + String.format("%.2f", getPrice());
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////

import java.io.File;

import java.io.FileNotFoundException;

import java.util.ArrayList;

import java.util.Scanner;



public class GroceryItemDemo {



    private static final double TAX = 5; // assuming the tax is 5% you may change it



    private static double calculateWithTax(double price) {



        return price * TAX / 100.0 + price; // calculate tax, add tax to the price and return it

    }



    public static void main(String[] args) {



        // update the input file name based on the location of the file in your system

        String inputFileName = "D:\\input.txt";

        ArrayList<GroceryItem> groceryItems = new ArrayList<>();

        try {

            Scanner fileReader = new Scanner(new File(inputFileName));

            String line;

            // read each line of the file once line at a time

            while (fileReader.hasNextLine()) {

                line = fileReader.nextLine();

                String data[] = line.split("\\s+"); // split the line by space character

                String itemName = data[0];

                double itemPrice = Double.parseDouble(data[1]);

                // create a groceryitem object using the values

                GroceryItem anItem = new GroceryItem(itemName, itemPrice);

                // store the object in  the array list

                groceryItems.add(anItem);

            }



            fileReader.close();

        } catch (FileNotFoundException e) {

            System.out.println("Error: Unable to open/read file: " + inputFileName);

            System.exit(1);

        }





        // print each item with the pre and post tax amount

        for (GroceryItem item : groceryItems) {

            System.out.println("Item Name: " + item.getName() +

                    ", Pre-Tax Price: $" + String.format("%.2f", item.getPrice()) +

                    ", Post-Tax Price: $" + String.format("%.2f", calculateWithTax(item.getPrice())));

        }





    }

}

/////////////////////////////////////////////////////////////////////////////////////////////


Related Solutions

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...
Write a Java class. The class name must be ShapeMetrics, which means the file name must...
Write a Java class. The class name must be ShapeMetrics, which means the file name must be ShapeMetrics.java. Provide the following functions: 1. getAreaOfRectangle(), with two float arguments, width and height, in that order, returning a float value which is the area of the rectangle with that width and height. 2. getSpaceDiagonalOfRectangularCuboid (), with three float arguments, width, height, and depth, in that order, returning a float value which is the length of the diagonal line which bisects the cuboid....
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...
public class MyLinked {    static class Node {        public Node (double item, Node...
public class MyLinked {    static class Node {        public Node (double item, Node next) { this.item = item; this.next = next; }        public double item;        public Node next;    }    int N;    Node first;     // remove all occurrences of item from the list    public void remove (double item) {        // TODO    } Write the remove function. Do NOT add any fields to the node/list classes, do...
Java Create an abstract Product Class Add the following private attributes: name sku (int) price (double)...
Java Create an abstract Product Class Add the following private attributes: name sku (int) price (double) Create getter/setter methods for all attributes Create a constructor that takes in all attributes and sets them Remove the default constructor Override the toString() method and return a String that represents the building object that is formatted nicely and contains all information (attributes) Create a FoodProduct Class that extends Product Add the following private attributes: expDate (java.util.Date) for expiration date refrigerationTemp (int) if 70...
Given the following Java source code fragment double price[]; price = new double[16]; What's the name...
Given the following Java source code fragment double price[]; price = new double[16]; What's the name of the array? How many elements are in the array? What's the index of the first element in the array? What's the index of the last element in the array? What's the value of the element at index 3 after the last statement executes?
Homework Assignment 4 Instructions: Class name must be: HW4_yourName For example: Michael will name the class...
Homework Assignment 4 Instructions: Class name must be: HW4_yourName For example: Michael will name the class of homework assignment 4 as HW4_Michael Grading Rubric: Code running and as per the required conditions and giving expected output = 10 points File named as per instructions = 1 point Comments in code = 4 points Problem: Average calculation for a list Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for...
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...
Exercise 3: Create a worksheet that gives a price quote. You will select an item name...
Exercise 3: Create a worksheet that gives a price quote. You will select an item name and enter the quantity of that item purchased. Use Data Validation to create a drop down list for your item names. Your worksheet should look up the item name in the Price Table to find the Unit Price. Then it should calculate the Total Before Discount. Look up this amount in the Discount Table to find the discount percent. Then your worksheet should calculate...
Create a class and name it MyArray. This class must have an internal array of integers...
Create a class and name it MyArray. This class must have an internal array of integers and the consumer should specify the maximum capacity when instantiating. MyArray class must provide following functions: 1- insert: This method receives and integer and inserts into the array. For simplicity you can assume the array is large enough and never overflows. 2- display: This method displays all integers stored in the array in the same order as they are inserted (first in first out)....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT