Question

Write a Java program in Eclipse that reads from a file, does some clean up, and...

Write a Java program in Eclipse that reads from a file, does some clean up, and then writes the “cleaned” data to an output file.

  • Create a class called FoodItem. This class should have the following:
    • A field for the item’s description.
    • A field for the item’s price.
    • A field for the item’s expiration date.
    • A constructor to initialize the item’s fields to specified values.
    • Getters (Accessors) for each field.
    • This class should implement the Comparable interface so that food items can be compared by date.
  • Create a text file called input.txt to contain a file of food items. Each line should be one and only one food item record and should have the following format, with each field being separated by white space:
    • The first field should be the description.
    • The second field should be the price.
    • The third field should be the expiration month.
    • The fourth field should be the expiration day.
    • The fifth filed should be the expiration year.
    • Create a file of twenty records.
    • The records must be in any unsorted order.
  • Create a Driver class that does the following:
    • Uses an ArrayList to store a collection of FoodItem objects.
    • Use a loop to read each record from the file. It may be easiest to read each record as an entire line, save it as a String and then use a scanner to scan the string for each field.
    • You need to create a Date object from the date fields. Fields: ( day = d; month = m; year = y;) and (int d, int m, int y)
    • You need to create a Food item object from each record and add it to your ArrayList.
    • You will then remove each food item from the ArrayList that has an expiration date before 5/1/2019. Remember, you need to use a while loop with an iterator to do this.
    • You will then sort then remaining food items by expiration date using Collections.sort.
    • You will then write each record remaining in the array list to a file called output.txt in the same format as specified for the input file.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

/********************************FoodItem.java****************************/

import java.util.Date;

public class FoodItem implements Comparable<FoodItem> {

   /*
   * data field
   */
   private String itemDesc;
   private double itemPrice;
   private Date expDate;

   /**
   *
   * @param itemDesc
   * @param itemPrice
   * @param expDate
   */
   public FoodItem(String itemDesc, double itemPrice, Date expDate) {
       super();
       this.itemDesc = itemDesc;
       this.itemPrice = itemPrice;
       this.expDate = expDate;
   }

   public String getItemDesc() {
       return itemDesc;
   }

   public double getItemPrice() {
       return itemPrice;
   }

   public Date getExpDate() {
       return expDate;
   }

   @Override
   public String toString() {
       return itemDesc + ", itemPrice=" + itemPrice + ", expDate=" + expDate;
   }

   @Override
   public int compareTo(FoodItem o) {

       if (this.expDate.after(o.expDate)) {
           return -1;
       } else if (this.expDate.before(o.expDate)) {
           return 1;
       } else {
           return 0;
       }
   }

}
/*****************************Driver.java***********************************************/

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;

public class Driver {

   public static void main(String[] args) {

       /*
       * array list to store food items
       */
       ArrayList<FoodItem> foodItems = new ArrayList<>();
       // to set date format
       DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
       /*
       * read file input.txt
       */
       File f = new File("input.txt");
       Scanner r = null;
       try {
           r = new Scanner(f);
           String line;
           int i = 0;
           while (r.hasNextLine()) {
               line = r.nextLine();
               String[] array = line.split(" ");

               String itemDesc = array[0];
               double itemPrice = Double.parseDouble(array[1]);
               int m = Integer.parseInt(array[2]);
               int d = Integer.parseInt(array[3]);
               int y = Integer.parseInt(array[4]);

               Date d1 = null;
               try {
                   d1 = df.parse(m + "/" + d + "/" + y);
               } catch (ParseException e) {
                   e.printStackTrace();
               }
               foodItems.add(new FoodItem(itemDesc, itemPrice, d1));

           }
       } catch (FileNotFoundException ex) {
           System.out.println("File not found!");
       }

       /*
       * show data of input.txt
       */
       for (FoodItem foodItem : foodItems) {

           System.out.println(foodItem.toString());
       }

       /*
       * remove item before 05/01/2019
       */
       Iterator<FoodItem> itr = foodItems.iterator();
       while (itr.hasNext()) {
           FoodItem item = (FoodItem) itr.next();
           try {
               if (item.getExpDate().before(df.parse("05/01/2019")))
                   itr.remove();
           } catch (ParseException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }

       /*
       * sort the array
       */
       Collections.sort(foodItems);

       /*
       * write to file
       */
       try {
           FileWriter fw = new FileWriter("output.txt");
           for (FoodItem foodItem : foodItems) {

               fw.write(foodItem.toString() + "\n");
           }
           fw.close();
       } catch (Exception e) {
           System.out.println(e);
       }
       System.out.println("Data Successfully written...");

   }
}
/*******************input.txt*****************************/

Butter 34.5 12 06 2018
Milk 34.5 02 10 2019
Juice 34.5 03 06 2019
Water 34.5 04 10 2019
Oil 34.5 11 09 2019
Biscuit 34.5 12 08 2019
Poison 34.5 06 07 2019
Butter 34.5 08 06 2018
Butter 34.5 09 06 2020
Juice 34.5 03 06 2018
Water 34.5 04 10 2018
Oil 34.5 11 09 2018
/******************************output.txt***************************/

Butter, itemPrice=34.5, expDate=Sun Sep 06 00:00:00 IST 2020
Biscuit, itemPrice=34.5, expDate=Sun Dec 08 00:00:00 IST 2019
Oil, itemPrice=34.5, expDate=Sat Nov 09 00:00:00 IST 2019
Poison, itemPrice=34.5, expDate=Fri Jun 07 00:00:00 IST 2019
/**********************console**************************/

Butter, itemPrice=34.5, expDate=Thu Dec 06 00:00:00 IST 2018
Milk, itemPrice=34.5, expDate=Sun Feb 10 00:00:00 IST 2019
Juice, itemPrice=34.5, expDate=Wed Mar 06 00:00:00 IST 2019
Water, itemPrice=34.5, expDate=Wed Apr 10 00:00:00 IST 2019
Oil, itemPrice=34.5, expDate=Sat Nov 09 00:00:00 IST 2019
Biscuit, itemPrice=34.5, expDate=Sun Dec 08 00:00:00 IST 2019
Poison, itemPrice=34.5, expDate=Fri Jun 07 00:00:00 IST 2019
Butter, itemPrice=34.5, expDate=Mon Aug 06 00:00:00 IST 2018
Butter, itemPrice=34.5, expDate=Sun Sep 06 00:00:00 IST 2020
Juice, itemPrice=34.5, expDate=Tue Mar 06 00:00:00 IST 2018
Water, itemPrice=34.5, expDate=Tue Apr 10 00:00:00 IST 2018
Oil, itemPrice=34.5, expDate=Fri Nov 09 00:00:00 IST 2018
Data Successfully written...
a Driver.java D Foodltem.java input.tt 0utput.txt X 1 Butter, itemPrice-34.5, expDate-Sun SeR 96 00:00:00 IST 2020 2 Biscuit,

Thanks a lot, Please let me know if you have any problem...................

Add a comment
Know the answer?
Add Answer to:
Write a Java program in Eclipse that reads from a file, does some clean up, and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 7.2 Write a Java program called to create an Excel spreadsheet Create a class called Food...

    7.2 Write a Java program called to create an Excel spreadsheet Create a class called Food to represent a Lunch food item. Fields include name, calories, carbs In a main method (of a different class), ask the user "How many things are you going to eat for lunch?". Loop through each food item and prompt the user to enter the name, calories, and grams of carbs for that food item. Create a Food object with this data, and store each...

  • The FoodItem.java file defines a class called FoodItem that contains instance variables for name (String) and...

    The FoodItem.java file defines a class called FoodItem that contains instance variables for name (String) and calories (int), along with get/set methods for both. Implement the methods in the Meal class found in Meal.java public class FoodItem{ private String name; private int calories;    public FoodItem(String iName, int iCals){ name = iName; calories = iCals; }    public void setName(String newName){ name = newName; }    public void setCalories(int newCals){ calories = newCals; }    public int getCalories(){ return calories;...

  • Write the following program in Java using Eclipse. A cash register is used in retail stores...

    Write the following program in Java using Eclipse. A cash register is used in retail stores to help clerks enter a number of items and calculate their subtotal and total. It usually prints a receipt with all the items in some format. Design a Receipt class and Item class. In general, one receipt can contain multiple items. Here is what you should have in the Receipt class: numberOfItems: this variable will keep track of the number of items added to...

  • Write a Gui programming by using JavaFx menus, stage and screen concepts to the RetailItem class,...

    Write a Gui programming by using JavaFx menus, stage and screen concepts to the RetailItem class, Write a class named Retailltem that holds data about an item in a retail store. The class should have the following fields description: The description field is a String object that holds a brief description of the item . unitsOnHand: The unitsOnHand field is an int variable that holds the number of units currently in inventory Price: The price field is a double that...

  • JAVA Write a program which will read a text file into an ArrayList of Strings. Note...

    JAVA Write a program which will read a text file into an ArrayList of Strings. Note that the given data file (i.e., “sortedStrings.txt”) contains the words already sorted for your convenience. • Read a search key word (i.e., string) from the keyboard and use sequential and binary searches to check to see if the string is present as the instance of ArraryList. • Refer to “SearchInt.java” (given in “SearchString.zip”) and the following UML diagram for the details of required program...

  • Write a program that performs the following: - Reads from the file "myfile.txt" using readlines() -...

    Write a program that performs the following: - Reads from the file "myfile.txt" using readlines() - Prints out the contents of the file "myfile.txt", that was read into a list by readlines(). Note that this should not look like a list, so you will need to loop through the list created by readlines and print the text. - Use the try/except method to create the file if it does not exist - If the file does not exist, prompt the...

  • Write in Java please. The purpose of this program is to read a file, called WaterData.csv....

    Write in Java please. The purpose of this program is to read a file, called WaterData.csv. It will output date and gallons. So it would look something like "2/04/15 40 Gallons". The pseudo code is as follows. prompt the user for a file name open the file if that file cannot be opened display an error message and quit endif create a String variable 'currentDate' and initialize it to the empty string. create a variable gallonsUsed and initialize it to...

  • Amusement Park Programming Project Project Outcomes Use the Java selection constructs (if and if else). Use...

    Amusement Park Programming Project Project Outcomes Use the Java selection constructs (if and if else). Use the Java iteration constructs (while, do, for). Use Boolean variables and expressions to control iterations. Use arrays or ArrayList for storing objects. Proper design techniques. Project Requirements Your job is to implement a simple amusement park information system that keeps track of admission tickets and merchandise in the gift shop. The information system consists of three classes including a class to model tickets, a...

  • Use BlueJ to write a program that reads a sequence of data for several car objects...

    Use BlueJ to write a program that reads a sequence of data for several car objects from an input file. It stores the data in an ArrayList<Car> list . Program should work for input file containing info for any number of cars. (You should not assume that it will always be seven lines in the input file). Use notepad to create input file "inData.txt". File should be stored in the same folder where all files from BlueJ for this program...

  • Write a program, called wordcount.c, that reads one word at a time from the standard input....

    Write a program, called wordcount.c, that reads one word at a time from the standard input. It keeps track of the words read and the number of occurrences of each word. When it encounters the end of input, it prints the most frequently occurring word and its count. The following screenshot shows the program in action: adminuser@adminuser-VirtualBox~/Desktop/HW8 $ wordCount This is a sample. Is is most frequent, although punctuation and capitals are treated as part of the word. this is...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT