【发布时间】:2016-01-18 08:01:30
【问题描述】:
我有一个随机生成的信息序列。我想将该信息保存在某种变量中,以便可以在其他地方调用它。我认为我想使用一个 ArrayList,但我不确定如何在 for 循环中添加信息(这是创建它的地方)。我的代码如下:
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);
}
我收到 NullPointerException。如果在这里使用 ArrayList 不是最好的,那会是什么?
感谢您提供的任何帮助。
【问题讨论】:
-
首先你错过了第一行的分号。您可以根据要求使用 arrayList 或任何适当的数据结构。要使用 arraylist,您需要先初始化它。 PhoneList = new ArrayList
();我在任何地方都没有看到声明的电话数组,也许它是引发 NullPointerException 的电话
标签: java android for-loop arraylist