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