简体   繁体   中英

Creating objects in an array for a menu

I'm trying to create a registration menu but I'm having trouble creating the objects in an accessible array. Super class constructor:

Login(String fn, String ln, String acc, String by, String pw){
    firstName = fn;
    lastName = ln;
    account = acc;
    birthYear = by;
    password = pw;
}

In the super class I created an array of type Login . In the child class Register , I'm trying to create objects in the array. My registration menu has several fields to be filled in. I want an error message to pop up when the fields are empty and when the password fields do not match.

JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        boolean match = false;
        while (match == false){
        if (textField_4.getText().equals(textField_5.getText())){
        try{
            for (int i = count; i<= list.length;i++){
            list[i] = new Login(textField.getText(),textField_1.getText(),textField_2.getText(),textField_3.getText(),textField_4.getText());
            count++;
            match = true;
            }}
            catch (Exception e){
                JOptionPane.showMessageDialog(null, "Fields are empty", "Error", JOptionPane.INFORMATION_MESSAGE);
                System.out.println(e);
                break;
            }
        }
        else
            match = false;
            JOptionPane.showMessageDialog(null, "Password fields do not match!", "Error", JOptionPane.INFORMATION_MESSAGE);
            break;
        }
    }
});

I have gotten the password mismatch feature to work but I currently get a ArrayIndexOutOfBounds thrown when I try to enter all of the fields and create an object. How do I resolve this issue? Thank you in advance.

The culprit is most likely these two lines

    for (int i = count; i<= list.length;i++){
    list[i] = ...

Trying to access " list[list.length] " will give you an ArrayIndexOutOfBounds , since indeces start at 0, so list 's last index is list.length-1 ;

Change from " i<= list.length " to " i < list.length ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM