对于一个项目,我正在编写一个有3个班级的程序:房屋,房间,温度。每个房屋都有一个或多个房间(对象的列表),每个房间都有一个温度(对象)。温度有2个变量:最高温度(两倍)和实际温度(两倍)。我需要制定一种方法来计算实际温度高于最高温度的时间。
所以我在HOUSE类中有此方法:
int getHighTempratures(){
return ....;
}
毕竟,我主要需要打印出类似以下内容: “您家中2个房间中的(1)个房间的温度高于最高温度”
(1):需要使用上面的方法来获取
我已经尝试使用Getter在House类的本地变量中存储实际温度。然后在主目录中打印此变量。
吸气剂根本不起作用。我是新来的,所以有点困难。我希望有人能帮助我。
温度等级:
public class Temperature {
private double ActualTemperature;
private double MaxTemperature;
public Temperature(double ActualTemperature, double MaxTemperature)
this.ActualTemperature = ActualTemperature;
this.MaxTemperature = MaxTemperature;
}
public double ActualTemperature() {
return ActualTemperature;
}
public double maxTemperature() {
return maxTemperature;
}
房间等级:
public class Room {
private String roomName;
private Temperature temperature;
public Room(String roomName, Temperature temperature) {
this.roomName = roomName;
this.temperature = temperature;
}
public String getroomName() {
return roomName;
}
public Temperature getTemperature() {
return temperature;
}
房屋类(我需要该方法的地方):
import java.util.ArrayList;
public class House {
private String street;
private int number;
private ArrayList<Room> rooms;
private int HighTempratures;
public House(String Street, int number) {
this.street = street;
this.number = number;
rooms = new ArrayList<Room>();
}
public void addRoom(Room rooms) {
rooms.add(rooms);
}
public int getHighTempratures() {
return HighTempratures;
}
创建了以下对象:
House house1 = new House (" St. street", 21);
Temperature temperature1 = new Temperature(20.0, 19.0);
Temperature temperature2 = new Temperature(22.7, 24.01;
Room room1 = new Room("Donovan", temperature1);
Room room2 = new Room("Jayden", temperature2);
house1.addRoom(room1);
house1.addRoom(room2);
所以:使用house类中的方法,我需要打印如下内容:在2个房间中的 1个房间中,其温度比最大房间高。
答案 0 :(得分:0)
如果您只需要一些过热的房间,可以这样进行:
public int getHighTempratures() {
int numberOfHighTemperatures = 0;
for (Room currentRoom: rooms) {
if(currentRoom.getTemperature().maxTemperature() < currentRoom.getTemperature().ActualTemperature() ){
numberOfHighTemperatures++;
}
}
/*
You can use this instead to make your code look better, but then you need to make method in Room class
for (Room currentRoom: rooms) {
if(currentRoom.isTooHot()){
numberOfHighTemperatures++;
}
}
*/
return numberOfHighTemperatures;
}
/*
//code to put into Room class to use prettier code
public boolean isTooHot(){
if(temperature.maxTemperature() < temperature.ActualTemperature()){
return true;
}
return false
}
*/
因此,总而言之,如果房间太热,则需要分别检查每个房间。
答案 1 :(得分:0)
根据PM 77-1的评论,在您的IsTooHot()
类中添加Room
方法将是一个简单的解决方案。
将以下方法添加到Room
:
// return boolean indicating if room temp is above max temp
public boolean isTooHot() {
return temperature.ActualTemperature() > temperature.maxTemperature();
}
House.getHighTemperatures()
变为:
int getHighTemperatures() {
int count = 0;
for (Room room : rooms) {
// increment count if room is too hot
if (room.isTooHot()) count++;
}
return count;
}