I have a DVD inventory record program that creates a DAT file if none exists and then stores the user input. As long as the program is running the user may then advance one record at a time (forward or back) through the files, skip at anytime to the first record or the last, and edit any file. Once the program closes I can open the file and view all of the saved files and they are there. The problem I have is that the next time the program is ran all that displays is the default values I established in the constructor (it is not pulling up my previously saved data). While my program meets all of my instructors requirements, it does not work in a useful manner. here are code snippets from my display and save sections.

//display
	public void displayDVD() {
		txt.setText("DVD Details:\n");
		txt.append("Item number: " + inv.get(currentDisplay).getDvdItem() + "\n");
		txt.append("DVD name: " + inv.get(currentDisplay).getDvdTitle() + "\n");
		txt.append("Units in stock: " + inv.get(currentDisplay).getDvdStock() + "\n");
		txt.append("Price: $" + String.format("%.2f",inv.get(currentDisplay).getDvdPrice()) + "\n");
		txt.append( "Runtime in minutes: " + inv.get(currentDisplay).getRuntime() + "\n");
		txt.append("Total value: $" + String.format("%.2f",inv.get(currentDisplay).value()) + "\n");
		txt.append("Fee: $" + String.format("%.2f",inv.get(currentDisplay).fee()) + "\n\n");
		txt.append("Total value: $" + String.format("%.2f",inv.value()));

    }

and

public void save() {
		save(true);
	}

	// save it to C:\data\inventory.dat
	public void save(boolean saveagain) {
		try {
			BufferedWriter w = new BufferedWriter(new FileWriter("c:\\data\\inventory.dat"));
			for (int i = 0; i < size(); i++) {
				DVDRuntime dvd = get(i);
				w.write("Item number: " + dvd.getDvdItem() + "\n");
				w.write("Item name: " + dvd.getDvdTitle() + "\n");
				w.write("Items in stock: " + dvd.getDvdStock() + "\n");
				w.write("Runtime: " + dvd.getRuntime() + "\n");
				w.write("Price: $" + dvd.getDvdPrice() + "\n");
				w.write("Fee: $" + dvd.fee() + "\n");
				w.write("Value (including the fee): $" + dvd.value() + "\n");
				w.newLine();
			}
			// total value of it
			w.write("Total fee: $" + (value() - value()/1.05) + "\n");
			w.write("Total value (including the fee): $" + value() + "\n");
			w.close();
		} catch (Exception ex) {
			if (saveagain) {
				new File("c:\\data\\").mkdir(); // make it if it wasn't there!
				save(false); // if it doesn't work now, we have a big problem!
			}// end IF
		}// end catch
	}//end method save

If more code is needed I can post it Thanks

Recommended Answers

All 10 Replies

The catch on line 24 seems far too general -so if you get an error acessing the data or converting it, or anything else, you always try to create a dircetory and try again. You should check for the exact exception that means you have a missing directory, then follow that with a second catch for "Exeception" that will catch everything else and allow you to treat it as a real error.

That is a great tip, however it is not that my DAT file is being overwritten, my problem is that the data saved on it is not being pulled up. I believe I need some form of "BufferedReader" code, and I have no idea where to insert it. I will post more of the program so maybe you or someone else will be able to decipher my problem

Since the code isn't posted, I can only ask questions.
Where in your code do you read the .dat file?
Does that code get called at program start up? How do you know that?
Where is the data from the .dat file read in?
Where is the data read in, moved to be displayed, replacing the default values?

Buffering the input doesn't make the data any more available. Buffering is an efficiency thing.

Have you tried debugging the code by using println()s to display what is happening?

Where in your code do you read the .dat file? ~~ Nowhere, that's the problem
Does that code get called at program start up? How do you know that?
Where is the data from the .dat file read in? ~~ again it is only read in to the file, not back into the program
Where is the data read in, moved to be displayed, replacing the default values? working on getting the code up so you can see

Buffering the input doesn't make the data any more available. Buffering is an efficiency thing.

Have you tried debugging the code by using println()s to display what is happening? no, my previous version used printline to display and enter data but did not save it at all

Here is my code (apologies for the length)

import java.awt.event.*;
import javax.swing.*;
import java.io.*;


public class InventoryApp extends JFrame{

	private JTextArea txt;
	private Inventory inv;
	private int currentDisplay = 0;

	public InventoryApp() {
		super ( "DVD Inventory Program" );
		setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		init();
	}

	private void init(){
	
		// create a default starter object
		DVDRuntime p1 = new DVDRuntime(0, " ", 0, 0, 0);

		//create an inventory and load the object
		inv = new Inventory();
		inv.add(p1);

		// graphical interface
		JPanel panel = new JPanel();
		txt = new JTextArea( 15,20 );
		txt.setEditable( false );//this is a display area so user should not change
		panel.add(txt);

		JPanel buttonpanel = new JPanel();
		buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS));


		JPanel anotherbuttonpanel = new JPanel();
		anotherbuttonpanel.setLayout(new BoxLayout(anotherbuttonpanel,BoxLayout.Y_AXIS));

		JButton first = new JButton("First");
		first.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				currentDisplay = 0;// go to the beginning
				displayDVD();
			}
		});
		buttonpanel.add(first);
		JButton previous = new JButton("Previous");
		previous.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (currentDisplay > 0) currentDisplay--;
				else currentDisplay = inv.size()-1;
				displayDVD();
			}
		});
		buttonpanel.add(previous);
		JButton next = new JButton("Next");
		next.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (currentDisplay < inv.size()-1) currentDisplay++; //advance to the end
				else currentDisplay = 0;
				displayDVD();
			}
		});
		buttonpanel.add(next);
		JButton last = new JButton("Last");
		last.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				currentDisplay = inv.size()-1;
				displayDVD();
			}
		});
		buttonpanel.add(last);

		JButton save = new JButton("Save");
		save.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				inv.save();
			}
		});
		anotherbuttonpanel.add(save);

		JButton search = new JButton("Search");
		search.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String str = JOptionPane.showInputDialog(InventoryApp.this,
				"Enter the name to search for");
				int result = inv.searchForDVDRuntime(str);
				if (result == -1) JOptionPane.showMessageDialog(InventoryApp.this,
				"Item Not found"); // do nothing
				else { // show the item
					currentDisplay = result;
					displayDVD();
				}
			}
		});
		anotherbuttonpanel.add(search);

		JButton add = new JButton("Add");
		add.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String name = JOptionPane.showInputDialog(InventoryApp.this,
				"Enter the DVD's Title");
				int units = Integer.parseInt(JOptionPane.showInputDialog(InventoryApp.this,
				"Enter the units in stock"));
				double price = Double.parseDouble(JOptionPane.showInputDialog(InventoryApp.this,
				"Enter the price of each item"));
				double runtime = Double.parseDouble(JOptionPane.showInputDialog(InventoryApp.this,
				"Enter the Runtime in minutes"));

				// make the object
				DVDRuntime dvd = new DVDRuntime(inv.highestNumber()+1, name, units, price, runtime);

				// put it in the inv, at the very end
				inv.addNewDVDRuntime(dvd);

				currentDisplay = inv.size()-1;
				displayDVD();
			}
		});
		anotherbuttonpanel.add(add);

		JButton modify = new JButton("Modify");
		modify.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// get new values and set them
				DVDRuntime dvd = inv.get(currentDisplay);
				dvd.setDvdItem(Integer.parseInt(
						JOptionPane.showInputDialog(InventoryApp.this,"Enter new item number",dvd.getDvdItem())));
				dvd.setDvdTitle(
						JOptionPane.showInputDialog(InventoryApp.this,"Enter new item name",dvd.getDvdTitle()));
				dvd.setDvdStock(Integer.parseInt(
						JOptionPane.showInputDialog(InventoryApp.this,"Enter new units in stock",dvd.getDvdStock())));
				dvd.setDvdPrice(Double.parseDouble(
						JOptionPane.showInputDialog(InventoryApp.this,"Enter new price of each item",dvd.getDvdPrice())));
				dvd.setRuntime(Double.parseDouble(
						JOptionPane.showInputDialog(InventoryApp.this,"Enter new Runtime in minutes",dvd.getRuntime())));

				// show it
				displayDVD();
			}
		});
		anotherbuttonpanel.add(modify);

		JButton delete = new JButton("Delete");
		delete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (inv.size() > 0) { // else there is nothing to delete
					inv.deleteDVDRuntime(inv.get(currentDisplay));
					currentDisplay--;
					if (currentDisplay < 0) currentDisplay = 0;
					displayDVD();
				}
			}
		});
		anotherbuttonpanel.add(delete);

		buttonpanel.add(new Logo());

		panel.add(buttonpanel);
		panel.add(anotherbuttonpanel);

		getContentPane().add(panel);

		displayDVD();

	} // end init

	//display
	public void displayDVD() {
		txt.setText("DVD Details:\n");
		txt.append("Item number: " + inv.get(currentDisplay).getDvdItem() + "\n");
		txt.append("DVD name: " + inv.get(currentDisplay).getDvdTitle() + "\n");
		txt.append("Units in stock: " + inv.get(currentDisplay).getDvdStock() + "\n");
		txt.append("Price: $" + String.format("%.2f",inv.get(currentDisplay).getDvdPrice()) + "\n");
		txt.append( "Runtime in minutes: " + inv.get(currentDisplay).getRuntime() + "\n");
		txt.append("Total value: $" + String.format("%.2f",inv.get(currentDisplay).value()) + "\n");
		txt.append("Fee: $" + String.format("%.2f",inv.get(currentDisplay).fee()) + "\n\n");
		txt.append("Total value: $" + String.format("%.2f",inv.value()));

    }



	public static void main(String args []){
		InventoryApp gui = new InventoryApp();
		gui.pack();
		gui.setVisible(true);
		} // end main

} // ends InventoryApp Class
public class DVD
{
	private int dvdItem;
	private String dvdTitle;
	private int dvdStock;
	private double dvdPrice;
	private double total;

	public DVD(int item, String title, int stock, double price)
	{
	dvdItem = item;
	dvdTitle = title;
	dvdStock = stock;
	dvdPrice = price;

	} //end four-argument constructor

	//default constructor
     // public DVD(){}

	// total value
		public double total(){
	return dvdPrice*dvdStock;
	}

	// getters and setters

	// set DVD Item
	public void setDvdItem(int item) {
	this.dvdItem = item;
	}

	//return DVD Item
	public int getDvdItem() {
	return dvdItem;
	}

	//set DVD Title
	public void setDvdTitle(String title) {
	this.dvdTitle = title;
	}

	//return Dvd Title
	public String getDvdTitle() {
	return dvdTitle;
	} //end method get Dvd Title

	public void setDvdStock(int stock) {
	this.dvdStock = stock;
	} //end method set Dvd Stock

	//return dvd Stock
	public int getDvdStock() {
	return dvdStock;
	} //end method get Dvd Stock

	public void setDvdPrice(double price) {
	this.dvdPrice = price;
	} //end method setdvdPrice

	//return DVD Price
	public double getDvdPrice() {
	return dvdPrice;
	} //end method get Dvd Price
	
} //end class DVD
public class DVDRuntime extends DVD{

    private double runtime = 0;

	 public DVDRuntime(int item, String title, int stock, double price, double runtime)
    {
        super( item,  title,  stock,  price);
		 this.runtime = runtime;
    }

    public double getRuntime() {
        return runtime;
    }

    public void setRuntime(double runtime) {
        this.runtime = runtime;
    }

	// Total value
	public double value() {
		return 1.05*getDvdPrice()*getDvdStock();
	}
	// fee
	public double fee() {
		return 0.05*getDvdPrice()*getDvdStock();
	}
}//end class DVDRuntime
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.*;

public class Inventory {
	private ArrayList<DVDRuntime> dvdlist;

	public Inventory() {
		dvdlist = new ArrayList<DVDRuntime>();
	}

	// adding and getting items

	public void add(DVDRuntime p) {
		dvdlist.add(p);
	}

	public int highestNumber() {
		int numb = 0;
		for (int i = 0; i < dvdlist.size(); i++) {
			if (get(i).getDvdItem() > numb) {
				numb = get(i).getDvdItem();
			}
		}
		return numb;
	}

	public DVDRuntime get(int i) {
		return dvdlist.get(i);
	}

	public int size() {
		return dvdlist.size();
	}

	public void sort() {
		// bubble sort
		int n = dvdlist.size();
		for (int search = 1; search < n; search++) {
			for (int i = 0; i < n-search; i++) {
				if (dvdlist.get(i).getDvdTitle().compareToIgnoreCase(dvdlist.get(i+1).getDvdTitle()) > 0) {
					// swap
					DVDRuntime temp = dvdlist.get(i);
					dvdlist.set(i,dvdlist.get(i+1));
					dvdlist.set(i+1,temp);
				}
			}
		}
	}

//	value
	public double value() {
		double total = 0.0;
		for (int i = 0; i < dvdlist.size(); i++) {
			total += get(i).value();
		}
		return total;
	}


	public void save() {
		save(true);
	}

	// save it to C:\data\inventory.dat
	public void save(boolean saveagain) {
		try {
			BufferedWriter w = new BufferedWriter(new FileWriter("c:\\data\\inventory.dat"));
			for (int i = 0; i < size(); i++) {
				DVDRuntime dvd = get(i);
				w.write("Item number: " + dvd.getDvdItem() + "\n");
				w.write("Item name: " + dvd.getDvdTitle() + "\n");
				w.write("Items in stock: " + dvd.getDvdStock() + "\n");
				w.write("Runtime: " + dvd.getRuntime() + "\n");
				w.write("Price: $" + dvd.getDvdPrice() + "\n");
				w.write("Fee: $" + dvd.fee() + "\n");
				w.write("Value (including the fee): $" + dvd.value() + "\n");
				w.newLine();
			}
			// total value of it
			w.write("Total fee: $" + (value() - value()/1.05) + "\n");
			w.write("Total value (including the fee): $" + value() + "\n");
			w.close();
		} catch (Exception ex) {
			if (saveagain) {
				new File("c:\\data\\").mkdir(); // make it if it wasn't there!
				save(false); // if it doesn't work now, we have a big problem!
			}// end IF
		}// end catch
	}//end method save

	// search by name
	public int searchForDVDRuntime(String title) {
		for (int i = 0; i < size(); i++) { // go through all the records
			if (get(i).getDvdTitle().equalsIgnoreCase(title)) return i;
		}
		return -1; // we didn't find anything
	}

	// add a new dvd
	public void addNewDVDRuntime(DVDRuntime dvd) {
		dvdlist.add(dvd);
	}

	// remove a dvd
	public void deleteDVDRuntime(DVDRuntime dvd) {
		dvdlist.remove(dvd);
	}
}

Here is my DAT file after running the program


*****************************************
Item number: 0
Item name:
Items in stock: 0
Runtime: 0.0
Price: $0.0
Fee: $0.0
Value (including the fee): $0.0

Item number: 1
Item name: Avatar
Items in stock: 12
Runtime: 111.0
Price: $29.99
Fee: $17.994
Value (including the fee): $377.874

Item number: 2
Item name: Big
Items in stock: 3
Runtime: 98.0
Price: $12.99
Fee: $1.9485000000000001
Value (including the fee): $40.9185

Item number: 3
Item name: Tombstone
Items in stock: 6
Runtime: 103.0
Price: $9.99
Fee: $2.9970000000000003
Value (including the fee): $62.93700000000001

Item number: 4
Item name: My Big Fat Greek Wedding
Items in stock: 10
Runtime: 90.0
Price: $8.54
Fee: $4.27
Value (including the fee): $89.66999999999999

Total fee: $27.209500000000048
Total value (including the fee): $571.3995
***********************************
(I added the ***"s for visual purposes)

Ah ha! I thought the code to read the file wasn't in th epart you displayed - I hadn't realised that it was completely missing!
So here's some simple guidance:
1. You write the file in a way that's very easy for a person to read, but harder for a computer to parse. Keep it simple. Write each DVD as a single line, with just the data, and a tab ("\t") between each field. Use a PrintWriter for simplicity.
Read the same file back in with a BufferedReader, one line at a time. Use the split(...) method from the String class to split each line back up into individual fields. Use those fields to (re)create the DVD objects.
All the other info you need is in the Java API doc for the classes & methods I mentioned.

My entire programming experience amounts to the duration of my one course so please bare with me. What you are asking/suggesting is that when I write the file to just include the relevant variables, and do so in one statement per instance of object DVD such as

write(dvd.getDvdItem, \tdvd.getDvdPrice, \tgetDvDSTUFF);

and to facilitate this better I could use PrintWriter over BufferedWritter.

Can you explain where in the code I should introduce the reader element, also can you provide a sample line of code for the reading and writing of the file.
Final question is: where/what is this Java API doc ?

Yes, you should write the file like in your example - obviously there's a bit more syntax needed to make that work - more like
myOutputFile.println(dvd.getDvdItem() + "\t" + ...
Where to introduce the reader? That depends on your requirements, but you should probably make it a little self-contained method, and call that right at the start of your program - if it that turns out not to be right you can easily move or duplicate the call to wherever else it needs to be.
You'll find loads of sample code on the web, so I'm not going to spend any time writing another sample - just use Google, and look for the simplest one you can find.

Thank you both Norm and James, I think I now have enough information to make something that will work =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.