I have created a Hostel class and a Room class, the Hostel class contains an ArrayList rooms, one value in this Arraylist is the Boolean available. In the Hostelclass i have created an if statement which is supposed to show any entry in the ArrayList where boolean available is true but instead it shows all values including those where available was false, but has now been changed to true. can anyone tell me where i have gone wrong.
public Room showAvail()
{
String theString = "Available Rooms";
if (Room.available == true)
for (Room room : rooms)
{
theString = theString + room.getRoomData() + "\n";
System.out.println(theString);
}
return null;
}
There are a few problems:
It seems that you’ve declared the variable
Room.availableas a static variable, thus as part of the class, not of the rooms. All rooms will share the same available status.The if statement is outside the loop, thus either the loop is executed for all rooms or for no rooms at all
You declare to return a Room, but then you always return null. Either return void or return a
List<Room>for the available rooms.You don’t need to test
if (variable == true), sinceif (variable)will do the same, although it won’t do any arm. (style)Use curly braces and indentation for the if statement, for added clarity. (style)
Here is a code fragment. I don’t know whether
theStringwill get all rooms or only those available, in the second case move it inside the if braces.