0

I have a class Bank

public class Bank {
    public static final double INTEREST = 0.1;  //Interest rate charged on overdrawn accounts
    private Vector customers=new Vector();
    private Address address;

    public Bank() {
        //address = null;
    }

    public Bank(Address add) {
        customers = new Vector ();
        address = add;
    }

    // add a Customer to the customers Vector
    public void addCustomer(Customer cus) {
        customers.add(cus);
    }

    // get and set methods
    public Vector getCustomers() {
        return customers;
    }

    public void setCustomers(Vector v) {
        customers = v;
    }

}

now i am adding customers to the Banks class

public void actionPerformed(ActionEvent e){
    int custnum=b.getBank().getCustomers().size()+1;
    ad=new Address(txtCustStreet.getText(),txtCustCity.getText(),txtCustPostCode.getText());
    cus=new Customer(txtCustName.getText(),ad,custnum, Integer.parseInt(txtoverdraft.getText()));

    if (e.getSource() == jbExit) {
        frame.dispose();
    }
    if (e.getSource() == jbSubmit) {
        // b.getBank().setCustomers(null);
        b.getBank().addCustomer(cus);
    }
    System.out.println(b.getBank().getCustomers().size());
}

when i am printing the vector size after adding 1 customers it prints 1 when i add two customers it prints like 1 2 while i add 3 customers it prints like 1 2 3

i want only only to print 3 when i add 3 customers not 1 2 3 please help me out thanks

4

1 回答 1

2

As MadProgrammer mentioned above it looks like you're using an actionPerformed method to add Customers. This would cause you to see:

1
2
3  

when you add 3 Customers because if you're doing this in an event handler then you must be triggering the event 3 times. Each of these ActionEvents being handled is triggering the actionPerformed method which has a System.out.println() call at the end of it. What's happening is that you're seeing all three numbers since each call is printing out the result of b.getBank().getCustomers().size() which is going up by one each time the method is called.

If you are triggering this with a button, try looking at your output between button clicks and you see that you'll have one line of output for each time you've clicked the button. If that's the case and you want to only see the final size of your Vector then you'll have to move your System.out.println() call outside of your event handling method.

于 2012-09-15T21:41:37.537 回答