简体   繁体   中英

How to add to ArrayList in a For loop

I have a sequence of information being randomly generated. I would like to save that information in a variable of some kind so that it can be recalled elsewhere. i think I want to use an ArrayList, but I'm not sure how to add the information while inside a for loop (which is where it is being created). The code I have is as follows:

public static ArrayList<String> phoneList

public static void main(String[] args){

    Random randomNumber = new Random();
    int howMany = randomNumber.nextInt(11);;
    String holding; 

    for (int i=0; i < howMany; i++){
        int itemRandNum = randomNumber.nextInt(11);//for all Item Categories
        int priceRandNum = randomNumber.nextInt(11);//Prices for all categories
        holding = phones[itemRandNum]+" $"+ priceOfPhones[priceRandNum]; 

        //System.out.println(holding);
        phoneList.add("holding"); //here is where I would like to add the information 
                                //contained in "holding" to the "phoneList" ArrayList.

    }

    System.out.println(phoneList);
}

I am getting a NullPointerException. If an ArrayList is not the best thing to use here, what would be?

Any help you can give is appreciated.

You get a NullPointerException because ArrayList phoneList is null since you didn't initialize it. Therefore write

public static ArrayList<String> phoneList = new ArrayList<>();

public static void String Main(String[] args) suggests this doesn't have much to do with Android.

First, instantiate the list (Outside your for loop):

phoneList = new ArrayList<>(howMany); //Adding "howMany" is optional. It just sets the List's initial size.

Then, add the values:

for (int i = 0; i < howMany; i++) {
    //...
    phoneList.add(holding); 
    //Don't place holding in quotation marks, else you'll just add "holding" for every entry!
}

As it is you are just declaring the class ArrayList not instantiating it. it is necessary for all the time you want to use a class to create an instance of the same class and thats simple, just do: public static ArrayList phoneList = new ArrayList() (if you are running older versions of java), otherwise use public static ArrayList phoneList = new ArrayList<>().

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