Android For循环填充数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3762887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For Loop to populate Array?
提问by roger
In the ImageAdapter class of this tutorial, http://developer.android.com/resources/tutorials/views/hello-gridview.html
在本教程的 ImageAdapter 类中,http://developer.android.com/resources/tutorials/views/hello-gridview.html
I would like to create and populate an array using a for loop. But it seems no matter where I place it, it causes an error.
我想使用 for 循环创建和填充数组。但似乎无论我把它放在哪里,都会导致错误。
For example, under private Context mContext;
I put in the following and it causes an error. I think the loop is good, I'm just not sure where I can put it.
例如,在private Context mContext;
I下输入以下内容并导致错误。我认为循环很好,我只是不确定我可以把它放在哪里。
private String[] myString;
for (int number = 0; number <= 12; number++) {
myString[number] = "image" + number;
}
private String[] myString;
for (int number = 0; number <= 12; number++) {
myString[number] = "image" + number;
}
回答by Nick
Create and populate the array in the constructor. Don't forget to actually instantiate the array before you start populating it.
在构造函数中创建并填充数组。不要忘记在开始填充数组之前实际实例化它。
public ImageAdapter(Context c) {
mContext = c;
myString = new String[12]; //create array
for (int number = 0; number < myString.length; number++) {
myString[number] = "image" + number;
}
}
You should perhaps work on your Java a bit before jumping straight into Android.
在直接进入 Android 之前,您或许应该先研究一下 Java。
回答by Macarse
It should be:
它应该是:
String[] myString = new String[12];
for (int number = 0; number <= 12; number++) {
myString[number] = "image" + number;
}
回答by RAJESH JEDI
public ImageAdapter(Context c)
{
mContext = c;
myString = new String[12]; //create array
for (int number = 0; number < myString.length; number++) {
myString[number] = "image" + number;
}
}