Member Avatar for buchanan23

Hi everyone.

So here is my dilemma, I am working on my final project, tackling it one item at a time, so this post is strictly for help deleting a record out of my array. I think I have everything set up right to call to a Method I am calling 'deleteBooks' The code doesn't compile right now because this is where I need help (Indicated by the "???WHAT GOES HERE???" line). I have searched through some examples and I am just not quite sure what to do in this method to delete the record. If anyone can push me in the direction that would be great! Thanks so much!

By the way, I don't care how it looks, I am not being graded on appearance but on functionality.

Brandon

File 1: "TestBooks.java"

import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.text.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;

public class TestBooks extends JFrame// define class
{
	public JButton firstButton;
	public JButton prevButton;
	public JButton nextButton;
	public JButton lastButton;
	public JButton saveButton;
	public JButton searchButton;
	public JButton addButton;
	public JButton modifyButton;
	public JButton deleteButton;
	DecimalFormat decimal = new DecimalFormat("$0.00");
        Books []arrayOfBooks;     
        int index=0;
	public int view;

        JLabel label1;
        JLabel isbnLabel;
        JLabel label2;
        JLabel label3;
        JLabel label4;
	JLabel label5;

   public TestBooks(Books[] arrayOfBooks)
   {
    super("Inventory GUI");
    JPanel topPanel= new JPanel();
    JPanel bottomPanel= new JPanel();
    topPanel.setLayout(new BoxLayout(topPanel,BoxLayout.Y_AXIS));
    bottomPanel.setLayout(new BoxLayout(bottomPanel,BoxLayout.Y_AXIS));
    this.arrayOfBooks=arrayOfBooks;
    Container con = getContentPane();
    con.add(topPanel, BorderLayout.NORTH);
    con.add(bottomPanel, BorderLayout.SOUTH);
		
	Books book = arrayOfBooks[0];

	label1 = new JLabel( "Title: " + book.getBookTitle() );
     	add( label1 );
       	isbnLabel = new JLabel( "ISBN: " + book.getBookIsbn() );
	add( isbnLabel );
	label2 = new JLabel( "Price: " + (decimal.format(book.getBookPrice())) );
     	add( label2 );
	label3 = new JLabel( "Quantity in stock: " + book.getBookQuantity() );
     	add( label3 );
	label4 = new JLabel( "Book Total: " + (decimal.format(book.getBookInventory())) );
     	add( label4 );
	label5 = new JLabel();
	add( label5);


	topPanel.add(label1);
	topPanel.add(isbnLabel);
	topPanel.add(label2);
	topPanel.add(label3);
	topPanel.add(label4);
	topPanel.add(label5);
	showBookRecord();
		
	firstButton = new JButton("|<<");
	firstButton.addActionListener(new FirstButtonHandler());
	firstButton.setToolTipText( "First Item" );
	bottomPanel.add(firstButton);

	prevButton = new JButton("<<");
	prevButton.addActionListener(new PrevButtonHandler());
	prevButton.setToolTipText( "Previous Item" );
	bottomPanel.add(prevButton);

	nextButton = new JButton(">>");
	nextButton.addActionListener(new NextButtonHandler());
	nextButton.setToolTipText( "Next Item" );
	bottomPanel.add(nextButton);

	lastButton = new JButton(">>|");
	lastButton.addActionListener(new LastButtonHandler());
	lastButton.setToolTipText( "Last Item" );
	bottomPanel.add(lastButton);

	saveButton = new JButton("Save");
	saveButton.addActionListener(new SaveButtonHandler());
	saveButton.setToolTipText("Save inventory to C:\\data\\inventory.dat");
	bottomPanel.add(saveButton);

	searchButton = new JButton("Search");
	//searchButton.addActionListener(new SearchButtonHandler());
	searchButton.setToolTipText("Search for an item in inventory.");
	bottomPanel.add(searchButton);

	addButton = new JButton ("Add");
	
	addButton.setToolTipText("Add an item to inventory.");
	bottomPanel.add(addButton);

	modifyButton = new JButton ("Modify");
	modifyButton.addActionListener(new ModifyButtonHandler()); 
	modifyButton.setToolTipText("Modify current item.");
	bottomPanel.add(modifyButton);

	deleteButton = new JButton ("Delete");
	deleteButton.addActionListener(new DeleteButtonHandler());
	deleteButton.setToolTipText("Delete current item.");
	bottomPanel.add(deleteButton);

     	pack();
     	setVisible( true);
   	
	}


	private class FirstButtonHandler implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			  index = 0;
                          showBookRecord();
  		  }
		}

	private class LastButtonHandler implements ActionListener{
		public void actionPerformed(ActionEvent e) { 
			  index = arrayOfBooks.length-1;
                          showBookRecord();
  		  }
		}

	private class NextButtonHandler implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			if (index<arrayOfBooks.length-1)
			{
				index++;
			}
			else
			{
				index=0;
			}
			showBookRecord();
		  }
		} 

	private class PrevButtonHandler implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			if (index>0)
			{
				index--;
			}
			else
			{
				index=arrayOfBooks.length-1;
			}
			showBookRecord();
		  }
		} 

	private class SaveButtonHandler implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			saveBooks();
		}
		}

	private class ModifyButtonHandler implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			modifyBooks();
		}
		}

	private class DeleteButtonHandler implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			deleteBooks();
		}
		}


         // New Method to display inventory information in GUI
         void showBookRecord() {

                if(index<0)
                     index=0;
                if(index>=arrayOfBooks.length)
                     index=arrayOfBooks.length - 1;

            	Books book = arrayOfBooks[index];
                 
		label1.setText("Title: " + book.getBookTitle() );
       		isbnLabel.setText( "ISBN: " + ((Books)book).getBookIsbn() );
		label2.setText("Price: " + (decimal.format(book.getBookPrice())) );
		label3.setText( "Quantity in stock: " + book.getBookQuantity() );
		label4.setText("Book Total: " + (decimal.format(book.getBookInventory())) );

		double bookTotal = 0.00;
  		for(int i=0; i<arrayOfBooks.length; i++) 
		{
            		bookTotal += arrayOfBooks[i].getBookInventory();
        	}
          	
		label5.setText("Inventory Total: " + String.valueOf(bookTotal) );
	}

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

	// New Method to save inventory information to file
	public void saveBooks(boolean attemptSave) {
		try {
		BufferedWriter w = new BufferedWriter(new FileWriter("c:\\data\\inventory.dat"));
		for (int i = 0; i < arrayOfBooks.length; i++) {
			Books save = arrayOfBooks[i];

			w.write("Title: " + save.getBookTitle() + "\n");
			w.write("ISBN: " + save.getBookIsbn() + "\n");
			w.write("Price: " + (decimal.format(save.getBookPrice())) + "\n");
			w.write("Quantity in stock: " + save.getBookQuantity() + "\n");
			w.write("Book Total: " + (decimal.format(save.getBookInventory())) + "\n");
			w.newLine();
		}
		// total value
		double bookTotal = 0.00;
  		for(int i=0; i<arrayOfBooks.length; i++) 
		{
            		bookTotal += arrayOfBooks[i].getBookInventory();
        	}
		
		w.write("Inventory Total: " + String.valueOf(bookTotal) + "\n");
		w.close();
		} catch (Exception ex) {
			if (attemptSave) {
				new File("c:\\data\\").mkdir(); // create directory if does not exist
				saveBooks(false);
			}
		}
		} 

	// New Method to modify an item in inventory
	public void modifyBooks(){
		
		Books book = arrayOfBooks[index];
		book.setBookTitle(JOptionPane.showInputDialog(TestBooks.this, "Enter Book Title: ", book.getBookTitle()));
		book.setBookIsbn(Integer.parseInt(
			JOptionPane.showInputDialog(TestBooks.this,"Enter ISBN: ",book.getBookIsbn())));
		book.setBookPrice(Double.parseDouble(
			JOptionPane.showInputDialog(TestBooks.this,"Enter Book Price: ",book.getBookPrice())));
		book.setBookQuantity(Integer.parseInt(
			JOptionPane.showInputDialog(TestBooks.this,"Enter Number of Books: ",book.getBookQuantity())));
		
		// display the new record
		showBookRecord();
	}

	// New Method to delete an item in inventory
	//???WHAT GOES HERE???
	
	
   	public static void main( String args[] )
   	{
    		 // This explains the program
     		System.out.println( "\nThis program will provide an inventory of books." );

     		// create Scanner to obtain input from command window
     		Scanner input = new Scanner( System.in );

     		// Prompt user for number of books to enter
     		System.out.println( "\nHow many books would you like to inventory today?" );
     		int numBooks = input.nextInt(); // Reads the data entered

     		Books[] bookArray = new Books[numBooks];

     		// set the total inventory value
     		double bookTotal = 0.00;

     		for (int i = 0; i < numBooks; i++)
     		{
       			Books book = new Books();
       			Scanner in = new Scanner( System.in );

         		// Request the book title
         		System.out.println( "\nPlease enter book title: " );
         		book.setBookTitle(in.nextLine()); // Reads the data entered
         		System.out.println( "\nPlease enter the ISBN for \"" + book.getBookTitle() + "\"" );
         		book.setBookIsbn(in.nextInt()); // Reads the data entered
         		System.out.println( "\nPlease enter the dollar amount for \"" + book.getBookTitle() + "\"" );
         		book.setBookPrice(in.nextDouble()); // Reads the data entered

         		System.out.println( "\nPlease enter the number of books currently in stock:" );
         		book.setBookQuantity(in.nextInt()); // Reads the data entered
         		System.out.println( "\nBook information entered successfully!" );

         		// marks the completion of 1 itteration of for loop
         		bookArray[i] = book;

     		} // end for loop that populates the array

     		TestBooks myFrame = new TestBooks(bookArray);
		myFrame.setSize( 400, 450 );
		myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		Graphic graphic = new Graphic();
		myFrame.add( graphic );


   }// end method main

}// end class TestBooks

2nd File: "Books.java"

//Checkpoint: Inventory Program Part 1
//This program will provide an inventory of books
//Brandon Buchanan

public class Books // define class
{
	private String bookTitle;
	private int bookIsbn;
	private double bookPrice;
	private int bookQuantity;


	//This constructor takes no arguments
	public Books(){

      	}   

      	//This constructor takes title, isbn, price, and quantity as arguments
     	public Books(String title, int isbn, double price, int quantity )
	{
		this.bookTitle=title;
		this.bookIsbn=isbn;
		this.bookPrice=price;
		this.bookQuantity=quantity;
	}

	public void setBookTitle(String title)
	{
		bookTitle = title;
	}

	public String getBookTitle()
	{
		return bookTitle;
	}

	public void setBookIsbn(int isbn)
	{
		bookIsbn=isbn;
	}

	public int getBookIsbn()
	{
		return bookIsbn;
	}

	public void setBookPrice(double price)
	{
		bookPrice=price;
	}

	public double getBookPrice()
	{
		return bookPrice;
	}

	public void setBookQuantity(int quantity)
	{
		bookQuantity=quantity;
	}

	public int getBookQuantity()
	{
		return bookQuantity;
	}

	public double getBookInventory()
	{
		return bookPrice * bookQuantity;
	}		
}

Now I haven't gone through your code, but if you are looking for a data structure which can hold a list and gives you the facility to delete any element at random I suggest you take a look at the followinf:-
ArrayList
HashSet
HashMap
TreeSet
TreeMap

However if you are hell bent on using just an "array", you will have to write you own functions to move data around in the array, overwriting any location which is deleted by moving the values from the behind indexes up one place etc.

By the way, I don't care how it looks, I am not being graded on appearance but on functionality.

Just a piece of advice do not concentrate on the grades so much that you forget the main motive of this subject being given to or taken up by you.

You'll need to pass the item to delete as a parameter. Loop thru the array until you hit that item, then continue thru the rest of the array moving each item down by 1 position. But, as stephen84 says, there are classes in theAPI that already do all that stuff, so why re-invent the wheel?

Member Avatar for buchanan23

You'll need to pass the item to delete as a parameter. Loop thru the array until you hit that item, then continue thru the rest of the array moving each item down by 1 position. But, as stephen84 says, there are classes in theAPI that already do all that stuff, so why re-invent the wheel?

Now I haven't gone through your code, but if you are looking for a data structure which can hold a list and gives you the facility to delete any element at random I suggest you take a look at the followinf:-
ArrayList
HashSet
HashMap
TreeSet
TreeMap

However if you are hell bent on using just an "array", you will have to write you own functions to move data around in the array, overwriting any location which is deleted by moving the values from the behind indexes up one place etc.


Just a piece of advice do not concentrate on the grades so much that you forget the main motive of this subject being given to or taken up by you.

Guys, thank you both for your comments, I didn't receive any quick replys here on this thread so I was forced to work through it, which was a GREAT thing and I got it all figured out.

Thanks.

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.