Reputation: 75
I have two classes is Room and Guest, I need to calculate the number of guests bookings in room to find suitable room. for example: guest A reservation for 5 people (guestnum) but we have three rooms: A1001 for 2 people(roomSeat), A1002 for 6 people (roomSeat) and A1003 for 8 people(roomSeat). We calculated as follows: |5-2|=3; |5-6|=1; |5-8|=3 => we choose rooms A1002 because it received the smallest value.
in class file processing:
public class Fileprocessing {
List<Room> resultInit = new ArrayList<Room>();
//List<Services> resultInit1 = new ArrayList<Services>();
List<Guest> resultThue = new ArrayList<Guest>();
List<TenantInformation> resultttkt= new ArrayList<TenantInformation>();
public Fileprocessing(){}
public List<TenantInformation> RoomforGuest(){
for (Guest g: this.resultThue){
int min=999999;
TenantInformation tt = new TenantInformation();
for (Room r: this.resultInit){
if(g.getGuestNum()-k.getRoomSeat()<min){
min=Math.abs(g.getGuestNum()-r.getRoomSeat());
tt.setGuestName(g.getGuestName());
tt.setRoomName(r.getRoomName());
r.setRoomStatus(1);
resultttkt.add(tt);
break;
}
}
}
System.out.println(resultttkt);
return resultttkt;
}
But it does not choose the room with the smallest value, it's just choose a room in order to read.
Upvotes: 1
Views: 78
Reputation: 19466
What you are doing right now is to see if the room capacity of any room is less than (999999) which is very likely to be true for all rooms, and then you break the loop. So you're going into your loop, sees that the first room found matches the criteria, and then you break the loop. You will always choose the first room in the list using this method.
You need to iterate through all rooms, then decide which room to use.
public List<TenantInformation> roomforGuest() {
for (Guest g: this.resultThue){
int min = Integer.MAX_VALUE;
Room selectedRoom = null;
TenantInformation tt = new TenantInformation();
for (Room r: this.resultInit) {
if(g.getGuestNum()-k.getRoomSeat() < min) {
min = Math.abs(g.getGuestNum() - r.getRoomSeat());
selectedRoom = r;
}
}
tt.setGuestName(g.getGuestName());
tt.setRoomName(selectedRoom.getRoomName());
selectedRoom.setRoomStatus(1);
resultttkt.add(tt);
}
}
I made a few other minor changes to your code.
min=999999
and not min=99999
? Use Integer.MAX_VALUE
to signify that all other numbers must be smaller than that.Also, what does r.setRoomStatus(1);
mean? What is 1? Don't use magic numbers — create an enum or create static variables on the Room class, e.g. final static int ROOM_OCCUPIED = 1
and use r.setRoomStatus(Room.ROOM_OCCUPIED);
instead.
Upvotes: 2