Solved

URGENT Java Array out of bounds exception

Posted on 2007-04-03
16
1,109 Views
Last Modified: 2013-12-14
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
0
Comment
Question by:manuman1968
  • 8
  • 5
  • 2
  • +1
16 Comments
 
LVL 8

Expert Comment

by:mnrz
ID: 18842090
put some System.out.println to display the index
it seems your index has an irrelevant value such as -1 or -2
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 18842109
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
0
 

Author Comment

by:manuman1968
ID: 18842170
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
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 18842187
Can you post your codes to add the new customer and the latest codes that you used to print out the customer?

David
0
 

Author Comment

by:manuman1968
ID: 18842194
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
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 18842197
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
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18842213
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
0
 

Author Comment

by:manuman1968
ID: 18842216
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
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 16

Expert Comment

by:suprapto45
ID: 18842236
Okay,

Where is the codes of populateCustomersNames();?

I guess that the problem occurred here.
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 18842251
I will be leaving in 10-15 mins...
0
 
LVL 10

Accepted Solution

by:
ADSLMark earned 500 total points
ID: 18842260
Just enclose this piece of code:

            //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();
            }

In a if where you check if the user selected an item yes/no:

if(customerComboBox.getSelectedIndex() > 0)
{
            //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();
            }
}
else
{
//.. if you want you can do sth here, but you do not have to.
}

Mark
0
 

Author Comment

by:manuman1968
ID: 18842273
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
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 18842306
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
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 18842309
and please try ADSLMark's solution too.
0
 

Author Comment

by:manuman1968
ID: 18842440
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
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 18842888
It should go to Mark only.

and glad that it worked.

David
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now