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...
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...
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...
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?
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)....
1. From the constructor, you infer that the name of the class containing the constructor must be_______ .
1. From the constructor, you infer that the name of the class containing the constructor must be_______ .2. Fill in the blanks so that the statement will instantiate a JButton object and assigns it to variable of JButton type:JButton btn= _______ ("OK");3. Fill in the blanks to complete the description of the constructor in the corresponding UML class diagram:+<>______( _____ : ______)
You must show the financial statement in all its parts including header, dollar signs and double...
You must show the financial statement in all its parts including header, dollar signs and double line in the totals. Points will be subtracted from the exercises if these parts are not completed properly. 7-14 Complete the balance sheet and sales information in the table that follows for Isberg Industries using the following finanacial data: Debt ratio: 50% Quick ratio: 0.80x Total assets turnover: 1.5x Days sales outstanding: 36.0 days Gross profit margin on sales: ( Sales - cost of...
International double taxation exists in its purest form when a single item of income is subject...
International double taxation exists in its purest form when a single item of income is subject to income is subject to income tax by more than one country. Discuss the four mechanisms presented in the text to eliminate or perhaps mitigate double taxation?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT