无法在 for 循环中向 ArrayList 添加元素 [英] Can't add element to ArrayList in for loop
问题描述
我目前遇到无法在 Android 应用开发中运行以下代码的问题.
I am currently having the problem of not able to run the following code in Android app development.
import java.util.ArrayList;
public class Test extends FragmentActivity {
ArrayList<String> random;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
for (int a=0; a<11; a++){
random.add("a");
}
}
}
我知道上面的代码做了无用的操作,但这是从我在 JAVA 中的 for 循环代码中的问题简化的.我从错误日志中得到了这个错误,未处理的事件循环异常".谁能指出我做错了什么?
I know the above code does useless action but that is simplified from my problem in the for loop code in JAVA. And I got this error from the error log, "unhandled event loop exception". Can anyone point out that what I am doing wrong please?
推荐答案
至少有两个问题(我怀疑).
There are at least two problems (I suspect).
首先,您得到一个 NullPointerException
,因为您没有使用引用实际对象的值初始化 random
.
First, you're getting a NullPointerException
because you're not initializing random
with a value referring to an actual object.
接下来,你的语法在这里很糟糕:
Next, your syntax is bad here:
for (int a=0; a<11; a++);
您的代码只是向 random
添加了一个元素 - 它相当于:
Your code is only adding a single element to random
- it's equivalent to:
for (int a=0; a<11; a++)
{
}
random.add("a");
我非常怀疑这就是您的意图.我的猜测是你想要这个:
I very much doubt that that's what you were intending. My guess is that you wanted this instead:
for (int a=0; a<11; a++)
{
random.add("a");
}
这篇关于无法在 for 循环中向 ArrayList 添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!