Results 1 to 2 of 2
  1. #1
    bdasilva is offline Member
    Join Date
    Jun 2009
    Posts
    1
    Rep Power
    0

    Default error running java program

    I am getting the error
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at LabelFrame.CalculateTotal(LabelFrame.java:336)
    at LabelFrame.LoadScreen(LabelFrame.java:326)
    at LabelFrame.<init>(LabelFrame.java:255)
    at BrettsInventory.main(BrettsInventory.java:9)

    when I try to run my program. I cannot figure out what the problem is. Here is the code for LabelFrame

    Java Code:
    import java.awt.GridLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    import java.util.NoSuchElementException;
    import java.io.ObjectInputStream;
    import java.io.EOFException;
    import java.io.FileInputStream;
    
    public class LabelFrame extends JFrame
    {
    
    private int recordCount=0;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    String fileName = "C:\\data\\inventory.dat";
    private boolean modifying = false;
    private boolean adding = false;
    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    
    private JTextField txtName;
    
    private JLabel label5;
    
    private JTextField txtUnits;
    
    private JLabel label7;
    private JTextField txtPrice;
    private JLabel label9;
    private JLabel label10;
    private JLabel label11;
    private JLabel label12;
    private JLabel label13;
    private JLabel label14;
    private JLabel label15;
    private JLabel label16;
    
    private JButton nextButton;
    private JButton firstButton;
    private JButton lastButton;
    private JButton previousButton;
    
    private JButton addButton;
    private JButton deleteButton;
    private JButton modifyButton;
    private JButton saveButton;
    private JButton searchButton;
    
    private int currentPosition;
    
    private Product[] pArray;
    
        public LabelFrame()
        {
    	super ("Inventory");
    
    
    
    
    
    
    
    
    
    
    
    
    	currentPosition =0;
    	// pArray = new Product[5];
    		//pArray[0]  = new Product(1, "Windows", 3, 164.99);
    		//pArray[1]  = new Product(2, "Door", 6, 345.78);
    		//pArray[2]  = new Product(3, "Plywood", 1, 1000.99);
    		//pArray[3]  = new Product(4, "Tile", 69, 497);
    		//pArray[4]  = new Paint(5, "Paint", 2, 20.00, "Yellow");
    
    	ReadRecords();
    
    	Product temp = pArray[currentPosition];
    	
    	setLayout( new GridLayout(10,4));
    	
    	ColorJPanel c = new ColorJPanel();		
    	add(c);
    	add(new JLabel(""));
    	add(new JLabel(""));
    	add(new JLabel(""));
    	add(new JLabel(""));
    
    	label1=new JLabel ("Item Number: ");
    	add (label1);
    
    	label2=new JLabel ("");
    	add (label2);
    
    	add(new JLabel(""));
    	add(new JLabel(""));
    	add(new JLabel(""));
    
    
    
    	label3=new JLabel ("Name: ");
    	add (label3);
    
    	txtName=new JTextField ("");
    	txtName.setEditable(false);
    	add (txtName);
    
    	add(new JLabel(""));
    	add(new JLabel(""));
    	add(new JLabel(""));
    
    
    	label5=new JLabel ("Units: ");
    	add (label5);
    
    	txtUnits = new JTextField("");
    	txtUnits.setEditable(false);
    	add (txtUnits);
    
    	add(new JLabel(""));
    	add(new JLabel(""));
    	add(new JLabel(""));
    
    
    	label7=new JLabel ("Price: ");
    	add (label7);
    
    
    	txtPrice = new JTextField("");
    	txtPrice.setEditable(false);
    	add (txtPrice);
    
    	add(new JLabel(""));
    	add(new JLabel(""));
    	add(new JLabel(""));
    
    
    	label9=new JLabel ("Value: ");
    	add (label9);
    
    
    	label10=new JLabel ("");
    	add (label10);
    
    	add(new JLabel(""));
    
    
    
    	label11=new JLabel ("Color: ");
    	add (label11);
    
    	label12=new JLabel ("");
    	add (label12);
    
    
    
    
    	label13=new JLabel ("Restocking Fee: ");
    	add (label13);
    
    	label14=new JLabel ("");
    	add (label14);
    
    	add(new JLabel(""));
    
    	add(new JLabel(""));
    	add(new JLabel(""));
    
    
    
    	label15=new JLabel ("Total Inventory:");
    	add (label15);
    	
    	label16=new JLabel ("");
    	add (label16);
    
    	add(new JLabel(""));
    	add(new JLabel(""));
    	add(new JLabel(""));
    
    
    
    	firstButton = new JButton("First");
    	add(firstButton);
    
    	previousButton = new JButton("Previous");
    	add(previousButton);
    
    	nextButton = new JButton("Next");
    	add(nextButton);
    
    	lastButton = new JButton("Last");
    	add(lastButton);
    
    
    	addButton = new JButton("Add");
    	add(addButton);
    
    	deleteButton = new JButton("Delete");
    	add(deleteButton);
    
    	modifyButton = new JButton("Modify");
    	add(modifyButton);
    
    	saveButton = new JButton("Save");
    	add(saveButton);
    
    	searchButton = new JButton("Search");
    	add(searchButton);
    
    
    	ButtonHandler handler = new ButtonHandler();
    	nextButton.addActionListener(handler);
    
    	FirstHandler fh = new FirstHandler();
    	firstButton.addActionListener(fh);
    
    	PreviousHandler ph = new PreviousHandler();
    	previousButton.addActionListener(ph);
    
    	LastHandler lh = new LastHandler();
    	lastButton.addActionListener(lh);
    
    	AddHandler ah = new AddHandler();
    	addButton.addActionListener(ah);
    
    	ModifyHandler mh = new ModifyHandler();
    	modifyButton.addActionListener(mh);
    	
    	SaveHandler sh = new SaveHandler();
    	saveButton.addActionListener(sh);
    
    	SearchHandler srh = new SearchHandler();
    	searchButton.addActionListener(srh);
    
    	DeleteHandler dh = new DeleteHandler();
    	deleteButton.addActionListener(dh);
    
    	LoadScreen();
    
        }
    
    private void Search(String toSearchFor)
    {
    	boolean found = false;
     	for(int i = 0; i< recordCount; i++)
    	{
    		if(pArray[i].getName().equals(toSearchFor))
    		{
    			found = true;
    			currentPosition =i;
    			LoadScreen();
    		}
    
    	}	
    	if(found == false)
    	{
    		JOptionPane.showMessageDialog(null, "Not found");
    	}
    }
    
    
    private int GetNextNumber()
    {
    	int next = 0;
    	for(int i = 0; i<recordCount; i++)
    	{
    		if(pArray[i].getNumber() > next)
    		{
    			next = pArray[i].getNumber();
    		}
    	}
    
    	return next+1;
    }
    
    private void LoadScreen()
    {
    	Product temp = pArray[currentPosition];
    	
    
    	label2.setText( String.format("%-10s", temp.getNumber()));
    
    
    
    
    	txtName.setText(temp.getName());
    
    
    	txtUnits.setText(String.format("%s", temp.getUnits()));
    
    
    	txtPrice.setText(String.format("%-10s", temp.getPrice()));
    
    
    	label10.setText(String.format("%-10s", temp.calculateInventory()));
    
    
    	label12.setText(temp.getColor());
    
    
    
    
    
    	label14.setText(String.format("%-10s", temp.getRestockingFee()));
    
    
    
    
    	label16.setText(String.format("%-10s", CalculateTotal(pArray)));
    
    
    }
    
    public static double CalculateTotal(Product[] theStuff)
    	{
    		double runningTotal =0;
    		for(int i=0; i<5; i++)
    		{
    			runningTotal = runningTotal + (theStuff[i].calculateInventory());
    		}
    		return runningTotal;
    	}
    	
    
    	//Sorta an array of Product classes
    	public static void bubbleSort(Product[] toSort) 
    	{
    		boolean keepSorting= true;
    		while (keepSorting) 
    		{
          			keepSorting = false;  // so that it will stop if there is no switch below
    	 		for (int i=0; i<4; i++) 
    			{
             			if (toSort[i].getName().compareTo(toSort[i+1].getName()) > 0) 
    				{
             				// exchange classes
             				Product temp = toSort[i];  
    					toSort[i] = toSort[i+1];  
    					toSort[i+1] = temp;
             				keepSorting= true;  // we had to switch something, better go again
             			}
    		        }
    		}
    	}
    
     	private class ButtonHandler implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
    			if(currentPosition ==recordCount-1)
    {
    			currentPosition =0;
    }
    else
    {
    currentPosition= currentPosition+1;
    }
    			
    			LoadScreen();
    		}
    	}
    
    
    private class FirstHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent event)
    	{
    		currentPosition =0;	
    		LoadScreen();
    	}
    }
    
    private class PreviousHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent event)
    	{
    		if(currentPosition == 0)
    		{
    
    			currentPosition =recordCount -1;
    		}
    		else
    		{
    			currentPosition = currentPosition -1;
    		}
    		LoadScreen();	
    	}
    }
    
    
    private class LastHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent event)
    	{
    		currentPosition =recordCount-1;
    		LoadScreen();
    	}
    	
    
    }
    
    private class ModifyHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent event)
    	{
    		txtName.setEditable(true);
    		txtUnits.setEditable(true);
    		txtPrice.setEditable(true);
    		modifying = true;
    	}
    	
    
    }
    
    private void DoModify()
    {
    	//take whatever is in the current position and update it's 3 editable fields
    	Product currentProduct = pArray[currentPosition];
    	currentProduct.setName(txtName.getText());
    	currentProduct.setUnits(Integer.parseInt(txtUnits.getText().trim()));
    	currentProduct.setPrice(Double.parseDouble(txtPrice.getText().trim()));
    	modifying = false;
    }
    
    
    private void DoAdd()
    {
    	//Create a new product array to hold whatever the user has added
    	Product newProduct = new Product(Integer.parseInt(label2.getText().trim()), txtName.getText(), 
    
    Integer.parseInt(txtUnits.getText().trim()), Double.parseDouble(txtPrice.getText().trim()));
    
    	//create an array to old all of the old class plus this new class
    	Product[] tempHolder = new Product[recordCount+1];
    	for(int i =0; i<recordCount; i++)
    	{
    		tempHolder[i] = pArray[i];
    	}
    	tempHolder[recordCount] = newProduct;
    	//add one to the recordCount
    	recordCount = recordCount+1;
    	pArray = new Product[recordCount];
    	//set the old array to be the same as this new array
    	for(int i = 0; i<recordCount; i++)
    	{
    		pArray[i] = tempHolder[i];
    	}
    	adding = false;
    
    	
    }
    
    private class AddHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent event)
    	{
    		//JOptionPane.showMessageDialog(null, "Adding");
    		//Get the next Number
    		int nextNumber = GetNextNumber();
    		//Put the number in the number lable
    		label2.setText(String.format("%-10s", nextNumber));
    		//Clear TextBoxes and Labels
    		txtName.setText("");
    		txtUnits.setText("");
    		txtPrice.setText("");
    		label10.setText("");
    		label12.setText("");
    		label14.setText("");
    		label16.setText("");
    		txtName.setEditable(true);
    		txtUnits.setEditable(true);
    		txtPrice.setEditable(true);
    		adding = true;
    		
    	}
    	
    
    }
    
    private class DeleteHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent event)
    	{
    		//JOptionPane.showMessageDialog(null, "Deleting");
    
    	Product newProduct = new Product(Integer.parseInt(label2.getText().trim()), txtName.getText(), 
    
    Integer.parseInt(txtUnits.getText().trim()), Double.parseDouble(txtPrice.getText().trim()));
    
    	//create an array to old all of the old classs except the current
    	Product[] tempHolder = new Product[recordCount-1];
    	for(int i =0; i<recordCount; i++)
    	{
    		if(i != currentPosition)
    		{
    			tempHolder[i] = pArray[i];
    		}
    		
    	}
    	
    	//subtract one fromt the record count
    	recordCount = recordCount-1;
    	pArray = new Product[recordCount];
    	//set the old array to be the same as this new array
    	for(int i = 0; i<recordCount; i++)
    	{
    		pArray[i] = tempHolder[i];
    	}
    
    		//update current
    		if(currentPosition ==0)
    		{
    			currentPosition = recordCount-1;
    		}
    		else
    		{
    			currentPosition = currentPosition -1;
    		}
    		//call the save
    		WriteRecords();
    		
    	}
    	
    
    }
    
    private class SearchHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent event)
    	{
    		//JOptionPane.showMessageDialog(null, "Searching");
    		String search=JOptionPane.showInputDialog(null, "Search:", "Search", 1);
    		Search(search);
    
    	}
    	
    
    }
    
    private class SaveHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent event)
    	{
    		txtName.setEditable(false);
    		txtUnits.setEditable(false);
    		txtPrice.setEditable(false);
    		if(modifying)
    		{
    			DoModify();
    		}
    		if(adding)
    		{
    			DoAdd();
    		}
    
    		WriteRecords();
    	}
    	
    
    }
    
    
    private void verifyFile()
    {
    
    
    	File file = new File(fileName); 
    	
    	File dir = new File("C:\\data\\");
    	if(!dir.isDirectory())
    	{
    		dir.mkdir();
    	}
    	
    
    
    	// Does the file already exist 
    	if(!file.exists()) 
    	{ 
    	  try 
    	  { 
    	    // Try creating the file 
    	    file.createNewFile(); 
    	  } 
    	  catch(IOException ex) 
    	  { 
    	    JOptionPane.showMessageDialog(null, "cannot create file" + fileName);
    	  } 
    	} 
    }
    
    
    private void OpenOutputFile()
    {
    	verifyFile();
    	try
    	{
    		output= new ObjectOutputStream( new FileOutputStream(fileName));
    	}
    	catch(IOException ex)
    	{
    		JOptionPane.showMessageDialog(null, "IO Exception opening output file");
    	}
    
    }
    
    private boolean OpenInputFile()
    {
    	verifyFile();
    	try
    	{
    		input = new ObjectInputStream( new FileInputStream(fileName));
    	}
    	catch(IOException ioException)
    	{
    		JOptionPane.showMessageDialog(null, "io exception verifying file");
    	}
    
    	return true;
    	
    }
    
    private void ReadRecords()
    {
    	//JOptionPane.showMessageDialog(null,String.format("%-10s", GetTotalRecords()));
    	int totalRecords = GetTotalRecords();
    	recordCount = totalRecords;
    	int currentRecord = 0;
    	if(totalRecords >0)
    	{
    		pArray = new Product[GetTotalRecords()];
    		OpenInputFile();
    		try
    		{
    			while(currentRecord<totalRecords)
    			{
    			
    			pArray[currentRecord] =(Product)input.readObject();
    			currentRecord++;
    			}
    		}
    		catch(EOFException ex)
    		{
    			return ;
    		}
    		catch(ClassNotFoundException ex1)
    		{
    			JOptionPane.showMessageDialog(null, "class not found");
    		}
    		catch(IOException ex2)
    		{
    			JOptionPane.showMessageDialog(null, "io exception here");
    		}
    	}
    
    	
    	
    }
    
    private int GetTotalRecords()
    {
    	int records=0;
    	if(OpenInputFile())
    	{
    try
    	{
    		while(true)
    		{
    		records = records+1;
    		Product x =(Product)input.readObject();
    		//JOptionPane.showMessageDialog(null, x.getName());
    		}
    	}
    	catch(EOFException ex)
    	{
    		return records-1;
    	}
    	catch(ClassNotFoundException ex1)
    	{
    		JOptionPane.showMessageDialog(null, "class not found");
    	}
    	catch(IOException ex2)
    	{
    		//JOptionPane.showMessageDialog(null, "io exception");
    		 //no records
    		return 0;
    	}
    	return records-1;
    	}
    	
    	return 0;
    }
    
    private void WriteRecords()
    {
    	OpenOutputFile();
    	try
    	{
    		for(int i = 0; i<recordCount; i++)
    		{
    			output.writeObject(pArray[i]);
    		}
    	}
    	catch (IOException ex)
    	{
    		JOptionPane.showMessageDialog(null, "IO exception");
    	}
    	catch (NoSuchElementException ex2)
    	{
    		JOptionPane.showMessageDialog(null, "no such element");
    	}
    }
    
    
    
    
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    That's a heck of a lot of non-compilable (for us) code to go through, but I'll take a stab at this. This method here smells dangerous to me:
    Java Code:
      public static double CalculateTotal(Product[] theStuff) {
        double runningTotal = 0;
        for (int i = 0; i < 5; i++) {
          runningTotal = runningTotal + (theStuff[i].calculateInventory());
        }
        return runningTotal;
      }
    since you are assuming that there will be 5 items in the Product array passed into it. What if there are only 4 items? Much safer is to let the array tell you how many times it should be looped like so:
    Java Code:
      public static double CalculateTotal(Product[] theStuff) {
        double runningTotal = 0;
        for (int i = 0; i < theStuff.length; i++) {
          runningTotal = runningTotal + (theStuff[i].calculateInventory());
        }
        return runningTotal;
      }

Similar Threads

  1. Same error msg with every program Java Textpad
    By peterdfl in forum New To Java
    Replies: 7
    Last Post: 04-17-2009, 05:49 AM
  2. Replies: 1
    Last Post: 01-12-2009, 09:59 AM
  3. [SOLVED] opening/running a program from java
    By xcallmejudasx in forum New To Java
    Replies: 3
    Last Post: 11-25-2008, 09:12 AM
  4. Replies: 0
    Last Post: 04-04-2008, 03:49 PM
  5. Running java program with arguments in Unix"
    By gvi in forum Advanced Java
    Replies: 2
    Last Post: 11-08-2007, 08:01 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •