如何使用while循环填充数组?

时间:2012-11-25 07:06:11

标签: java listview

我有一段像这样的代码,我想用一段时间来插入数据。

Weather weather_data[] = new Weather[]{
                new Weather(0, "Cloudy"),
                new Weather(0, "Showers"),
                new Weather(0, "Snow"),
                new Weather(0, "Storm"),
                new Weather(0, "Sunny")
};

如何使用一段时间填写此列表?

谢谢

3 个答案:

答案 0 :(得分:3)

试试这个:

Weather weather_data[] = new Weather[5];

int i = 0;
while(i < weather_data.length){
    //fill array [i]
    i++;
}

答案 1 :(得分:2)

据我所知,您希望使用以下String数组作为基数来填充数组:

String[] weatherTypes = {"Cloudy","Showers","Snow","Storm","Sunny"};

然后你可以这样做:

int i=0;
Weather[] weather_data = new Weather[];
for (String weatherType: weatherTypes){
   weather_data[i] = new Weather(0,weatherType);
   i++;
}

您也可以使用列表:

List<Weather> weather_data = new ArrayList<Weather>();
for (String weatherType: weatherTypes){
   weather_data.add(new Weather(0,weatherTypes));
}

答案 2 :(得分:0)

Weather[] weather_data = new Weather[5];

public void addWeatherData(Weather newWeather) {
    int counter = 0;
    while (counter < weather_data.length) {
        if (weather_data[counter] == null) {
            weather_data[counter] = newWeather;
            return;
        }
        counter++;
    }
}