java定义WeatherDemo类,实现main方法,包含以下功能: 建立一个Weather类的ArrayList列表对象。 从屏幕读入一个整数n,代表天数。 在列表对象中插入n个的Weather对象,即n天的天气情况。 遍历列表,把所有对象的温度、湿度输出(使用for)。 遍历列表,把所有对象的温度、湿度输出(使用增强for)。 遍历列表,把所有对象的温度、湿度输出(使用迭代器)。 遍历列表,统计列表对象中comfortable的天数,并输出。
时间: 2024-04-09 10:29:11 浏览: 13
以下是使用Java定义的WeatherDemo类,实现了main方法,并包含了上述功能:
```java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class WeatherDemo {
public static void main(String[] args) {
ArrayList<Weather> weatherList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.print("请输入天数:");
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
Weather weather = new Weather();
weatherList.add(weather);
}
System.out.println("使用for循环遍历列表,输出温度和湿度:");
for (int i = 0; i < weatherList.size(); i++) {
Weather weather = weatherList.get(i);
weather.print();
}
System.out.println("使用增强for循环遍历列表,输出温度和湿度:");
for (Weather weather : weatherList) {
weather.print();
}
System.out.println("使用迭代器遍历列表,输出温度和湿度:");
Iterator<Weather> iterator = weatherList.iterator();
while (iterator.hasNext()) {
Weather weather = iterator.next();
weather.print();
}
int comfortableCount = 0;
for (Weather weather : weatherList) {
if (weather.isComfortable()) {
comfortableCount++;
}
}
System.out.println("在列表中comfortable的天数为:" + comfortableCount);
}
}
```
在WeatherDemo类中,首先创建了一个Weather类的ArrayList列表对象 weatherList。然后从屏幕读入一个整数n,代表天数。接着使用for循环插入n个Weather对象到列表中,即n天的天气情况。
接下来,使用for循环、增强for循环和迭代器三种方式遍历列表对象,分别输出每个对象的温度和湿度。
最后,使用for循环统计列表对象中comfortable的天数,并将结果输出。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)