Mallory Reese Mallory Reese - 5 months ago 10
Java Question

Trying to write a method to create an array list

I'm using Netbeans/GUI to make a fantasy basketball game program. I'm trying to create methods that create arraylists, that way I can call the method for the array every time I need it for one of my button events, rather than recode the array under each individual event. The array list method loads up data for the team name from a listbox I created in the design window. Code is as follows:

public class JFMarchMadness extends javax.swing.JFrame {

public JFMarchMadness()
{
initComponents();
}

//creates arraylist and loads up data from arraylist of type string (lstConfTeams)
void createCTArrayList ()
{
ArrayList<BasketballTeam> alCTeams=new ArrayList <>();

String CTteamName;
String CTstatus="";
int CTwins=0;
int CTlosses=0;
double CTwinLossPct=0;

for (int iCount = 0; iCount <lstConfTeams.getModel().getSize(); iCount++)
{
CTteamName=lstConfTeams.getModel().getElementAt(iCount);
alCTeams.add(new BasketballTeam(CTstatus,CTteamName,CTwins,CTlosses,CTwinLossPct));
}

}

private void btnPlayMouseClicked(java.awt.event.MouseEvent evt) {
// call createCTArrayList method and begin for loop


createCTArrayList ();

int iCTCount;

for (iCTCount=0; iCTCount<alCTeams.size; iCTCount++){
//
}
}


Right now it gets an error where it can't find the arraylist: alCTeams when I try to call it in the for loop statement. Did I write the method incorrectly or am I calling it incorrectly?

Answer

The declaration for alCTeams should be located under the class not the method.

Like this:

public class JFMarchMadness extends javax.swing.JFrame {

ArrayList<BasketballTeam> alCTeams=new ArrayList <>();

public JFMarchMadness() 
{
    initComponents();
}

//creates arraylist and loads up data from arraylist of type string (lstConfTeams)
void createCTArrayList ()
{
    String CTteamName;
    String CTstatus="";
    int CTwins=0;
    int CTlosses=0;
    double CTwinLossPct=0;

    for (int iCount = 0; iCount <lstConfTeams.getModel().getSize(); iCount++)
    {
        CTteamName=lstConfTeams.getModel().getElementAt(iCount);
        alCTeams.add(new BasketballTeam(CTstatus,CTteamName,CTwins,CTlosses,CTwinLossPct));
    }

}

private void btnPlayMouseClicked(java.awt.event.MouseEvent evt) {                                     
// call createCTArrayList method and begin for loop


    createCTArrayList ();

    int iCTCount;

    for (iCTCount=0; iCTCount<alCTeams.size; iCTCount++){
    //
    }
}
Comments