编写Weather类:
(1)包含两个属性:温度(temperature)、湿度(humidity)
(2)无参构造方法:使用Random类,随机生成一个035之间的整数赋值给温度,随机生成一个3080之间的整数赋值给湿度。
(3)成员方法:
isComfortable:如果温度在1525度间,湿度在5070间则返回true,否则返回false。
print:输出温度、湿度。
编写WeatherDemo类,实现main方法,包含以下功能:
(1) 建立一个Weather类的ArrayList列表,并在列表中插入1个月(30个)的Weather对象
(2) 遍历列表,把所有对象的温度、湿度输出。
(3) 遍历列表,统计这个月中comfortable的天数,并输出。
import java.util.Random;
public class Weather {
int T,H;
public Weather() {
Random d=new Random();
T=d.nextInt(36);
H=d.nextInt(51)+30;
}
public boolean isComfortable() {
if(T>=15&&T<=25&&H>=50&&H<=70)
return true;
else
return false;
}
public void print() {
System.out.println("温度为:"+T+'\n'+"湿度为:"+H);
}
import java.util.ArrayList;
public class WeatherDemo {
public static void main(String[] args) {
ArrayList<Weather> a=new ArrayList<Weather>();
for(int i=0;i<30;i++){
a.add(new Weather());
}
Weather s;
for(int i=0;i<a.size();i++){
s=a.get(i);
System.out.println("温度为:"+s.T+" "+"湿度为:"+s.H);
}
int f=0;
for(int i=0;i<a.size();i++){
s=a.get(i);
if(s.isComfortable())
f++;
}
System.out.println("这个月comfortable的天数为:"+f);
}
}
运行结果: