Link to home
Start Free TrialLog in
Avatar of manuman1968
manuman1968

asked on

URGENT Java Array out of bounds exception

Hi experts.
I have a problem, i am working on an assignment for a banking system and have run into an exception problem that i am struggling to overcome and i am allready past my deadline, so this is very urgent. The following is the exception:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
this exception is showing as being in my Branch class as below

public Customer getCustomerAt( int index )
        {
           
            
            if( index >= theCustList.length)
                  return null;
            else
                  return theCustList[index];
      }
and in my GUI class as below

currentSelectedCustomer = branch.getCustomerAt(customerComboBox.getSelectedIndex());

The app works fine when i am viewing and performing operations on customers that i built as default into the system for testing, however as soon as i try to add a new customer to the system the combobox that displays the customers for selection goes blank and the exception is thrown. I have been trying to sort this for days now and i am lost. I am comiling the program in Netbeans 5.5 IDE but have also tried it in Eclipse in case it was a Netbeans bug ( I know im desperate) but with the same results. Can anybody help me urgentley. 500 points. Thanks in advance
Avatar of mnrz
mnrz

put some System.out.println to display the index
it seems your index has an irrelevant value such as -1 or -2
Is the logic right?

When the index is greater than theCustList.length, you return null but when it is less than theCustList.length which could be negative values, you return theCustList[index].

I just do not feel that it is correct logic.

David
Avatar of manuman1968

ASKER

Yes the error message shows that when i try to add a customer the array has an index of -1.
When i try to put a print ln in i can for viewing the customers but when i try to add i just get the error message again and no print out. I have tried putting a printline in  both at the customer index and also in the gui for the combo box. Below is what i get

Blackburn Branch now has 4 customer(s)
Elihe.Customer@145d068
Elihe.Customer@3e86d0
Elihe.Customer@a39137
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
        at Elihe.Branch.getCustomerAt(Branch.java:70)
        at Elihe.BankFrame.actionPerformed(BankFrame.java:204)
        at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1197)
        at javax.swing.JComboBox.contentsChanged(JComboBox.java:1268)
        at javax.swing.JComboBox.intervalRemoved(JComboBox.java:1288)
        at javax.swing.AbstractListModel.fireIntervalRemoved(AbstractListModel.java:161)
        at javax.swing.DefaultComboBoxModel.removeAllElements(DefaultComboBoxModel.java:169)
        at javax.swing.JComboBox.removeAllItems(JComboBox.java:745)
        at Elihe.BankFrame.populateCustomersNames(BankFrame.java:125)
        at Elihe.BankFrame.actionPerformed(BankFrame.java:219)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:5488)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
        at java.awt.Component.processEvent(Component.java:5253)
        at java.awt.Container.processEvent(Container.java:1966)
        at java.awt.Component.dispatchEventImpl(Component.java:3955)
        at java.awt.Container.dispatchEventImpl(Container.java:2024)
        at java.awt.Component.dispatchEvent(Component.java:3803)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
        at java.awt.Container.dispatchEventImpl(Container.java:2010)
        at java.awt.Window.dispatchEventImpl(Window.java:1778)
        at java.awt.Component.dispatchEvent(Component.java:3803)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
 I appear to be gaining a customer from somewhere as a println i added earlier to try to find the fault shows the system as having 4 customers when in fact there are only the default 3.
 Any ideas, i know i am getting a wrong index when i try to add a new customer but i do not know how to correct it.
Many Thanks
Can you post your codes to add the new customer and the latest codes that you used to print out the customer?

David
Hi David,
That sounds exactly like what my problem is. I am new to programming and do not know how to get round the problem. What should the correct logic be there.
Thanks
Not a problem,

As long as you show us that you put the efforts to do it, we will be happy to help.

Can you post the complete codes so that we can have a look?

David
Problem is in this line:
currentSelectedCustomer = branch.getCustomerAt(customerComboBox.getSelectedIndex());
This returns -1 if nothing is selected.
First check whether the user selected something with:
if (customerComboBox.getSelectedIndex() > 0)
{
//... ok user selected something
}
else
{
//... nothing selected
}

See:
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComboBox.html#getSelectedIndex()

Mark
Here are the codes David. I am actually using a gui to display the customers
This is the code for the administration of a branch where i add customers

/*
 * Branch.java
 *
 * Created on 14 March 2007, 10:29
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Elihe;

/**
 *
 * @author brian britwell
 */
public class Branch{
      
      private String theName;
      private Customer[] theCustList;
      private int numCustomers;
      private int maxCustomers;


      /** Creates a new instance of Branch */

      public Branch(String aName, int maxNum){ //Constructor method
            maxCustomers = maxNum;
            theCustList = new Customer[maxCustomers];
            theName = aName;
      }

      public boolean addCustomer(Customer newCustomer) {
            //if there is more place for the new customer...
            if (numCustomers < maxCustomers) {
                  theCustList[numCustomers] = newCustomer;                  
                  numCustomers++;
                  System.out.println(theName);
                  System.out.println("New customer added");
                  System.out.println( theName + " now has " + (numCustomers+1) + " customer(s)");
                  return true;
            } else {
                  System.out.println("New customer not added");
                  System.out.println( theName + " already has a full set of customers");
                  return false;
            }
      }

      //Selector methods      
      public String getName() {
            return theName;
      }

      public int getNumCustomers() {
            return numCustomers;
      }

      public Customer[] getCustomers() {
            return theCustList;
      }

      //returns the customer at the specified location
      public Customer getCustomerAt( int index )
        {
           
            
            if( index >= theCustList.length)
                  return null;
               
            else
                  //  System.out.println(theCustList[index]);
                  return theCustList[index];
               
      }
      
      public void printCustomersDetails() {
            System.out.println("Customers for branch: " + theName);
            
            for (int i = 0; i < theCustList.length; i++)                   
                  theCustList[i].printCustomerDetails();
            
            System.out.println("---------------------------");
      }
}

This is from the GUI for viewing the default Cutomers

public void actionPerformed(ActionEvent event){
            
            //depending on the control that trigged the event...do some action            
            if(event.getSource() == customerComboBox ){
                  //get the customer from the branch, and store it locally
                        System.out.println(branch.getCustomerAt(customerComboBox.getSelectedIndex()));
                  currentSelectedCustomer = branch.getCustomerAt(customerComboBox.getSelectedIndex());
                         
                  //print it's name in the field
                  customerNameTextField.setText(currentSelectedCustomer.getName());
                  //prints in the frame the details of the current selected account of the current selected customer                  
                  putOnScreenAccountDetails();
            }

and this is when i try to add new customers

else
            if(event.getSource() == addCustomerButton ){
                        populateCustomersNames();
                  //create customer
                  Customer c1 = new Customer(customerNameTextField.getText());
                  
                  //create one of the each type of account for customer, with some default values
                  CreditCardAccount cca1 = new CreditCardAccount("cca"+branch.getNumCustomers(),0,100,5);                  
                  SavingsAccount sa1 = new SavingsAccount("sa"+branch.getNumCustomers(),0,5);                   
                  CurrentAccount ca1 = new CurrentAccount("ca"+branch.getNumCustomers(),0,300);
                  
                  //set the accounts to the customer
                  c1.setCreditCardAccount(cca1);
                  c1.setCurrentAccount(ca1);
                  c1.setSavingsAccount(sa1);
                  
                  //add the customer to the branch
                  branch.addCustomer(c1);
                  
                  //called to put the customers name into the combobox (repopulate)
                  populateCustomersNames();
            }

And this for displaying the details in the GUI

private void putOnScreenAccountDetails(){
            //depending on the account type....
            if(accountTypeComboBox.getSelectedIndex() == 0){
                  CreditCardAccount acc = currentSelectedCustomer.getCreditCardAccount();
                  accountNumberTextField.setText(acc.getAccNumber());
                  balanceTextField.setText(""+acc.getBalance());
                  detailsTextField.setText("Limit: " + acc.getLimit() +", Rate: " + acc.getSavingsRate());
            }
            else
                  if(accountTypeComboBox.getSelectedIndex() == 1){
                        CurrentAccount acc = currentSelectedCustomer.getCurrentAccount();
                        accountNumberTextField.setText(acc.getAccNumber());
                        balanceTextField.setText(""+acc.getBalance());
                        detailsTextField.setText("Limit: " + acc.getLimit());
                  }
                  else
                        if(accountTypeComboBox.getSelectedIndex() == 2){
                              SavingsAccount acc = currentSelectedCustomer.getSavingsAccount();
                              accountNumberTextField.setText(acc.getAccNumber());
                              balanceTextField.setText(""+acc.getBalance());
                              detailsTextField.setText("Rate: " + acc.getSavingsRate());
                        }
      }

Thanks hope you can help
Okay,

Where is the codes of populateCustomersNames();?

I guess that the problem occurred here.
I will be leaving in 10-15 mins...
ASKER CERTIFIED SOLUTION
Avatar of ADSLMark
ADSLMark

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Codes for populateCustomersNames

//called to put the customers name into the combobox
      private void populateCustomersNames(){
            //read all the customers from the branch
            Customer[] cust = branch.getCustomers();
            //clear previous ones
            customerComboBox.removeAllItems();
            //add each name
            for( int i = 0 ; i < branch.getNumCustomers() ; i++ ){
                  customerComboBox.addItem(cust[i].getName());
            }
      }

Again Thanks
Sorry,

I got to go now for a meeting. I will have a look at this later. Hopefully, by then, this has been solved by someone here.

David
and please try ADSLMark's solution too.
Thanks Mark
Thats fixed it, i just need to sort the index numbering now for my display.
Who should i award the points to, yourself or split them as you have both helped.
Again many thanks from a newcomer
It should go to Mark only.

and glad that it worked.

David