--Java Program-- You are to create a class called PeopleInRooms that can be used
ID: 3668283 • Letter: #
Question
--Java Program--
You are to create a class called PeopleInRooms that can be used to record the number of people in the rooms of a building.
The class has the attributes:
• peopleInARoom - the number of people in a room
• peopleInAllRooms - the total number of people in all rooms as a static variable
The class has the following methods:
• addOneToRoom - adds a person to the room and increases the value of peopleInAllRooms
• removeOneFromRoom - removes a person from the room, ensuring that peopleInARoom does not go below zero, and decreases the value of peopleInAllRooms as appropriate
• getNumberPeopleInARoom - returns the number of people in a room
• getNumberPeopleInAllRooms - a static method that returns the total number of people
The output is:
Room A holds 2
Room B holds 3
Total in all rooms is 5
Remove two from both rooms
Room A holds 0
Room B holds 1
Total in all rooms in 1
Remove two from Room A
Room A holds 0
Room B holds 1
Total in all rooms in 1
Explanation / Answer
class PeopleInRooms {
int peopleInARoom;
static int peopleInAllRooms;
public void addOneToRoom(){
peopleInARoom++;
peopleInAllRooms++;
}
public void removeOneFromRoom(){
if(peopleInARoom == 0)
return;
peopleInARoom--;
peopleInAllRooms--;
}
public int getNumberPeopleInRoom(){
return peopleInARoom;
}
public static int getNumberPeopleInAllRooms(){
return peopleInAllRooms;
}
}
class TestPeopleInRooms{
public static void main(String[] args) {
PeopleInRooms a = new PeopleInRooms();
PeopleInRooms b = new PeopleInRooms();
//adding 2 room to a
a.addOneToRoom();
a.addOneToRoom();
//adding 3 room to b
b.addOneToRoom();
b.addOneToRoom();
b.addOneToRoom();
System.out.println("Room A holds "+a.getNumberPeopleInRoom());
System.out.println("Room B holds "+b.getNumberPeopleInRoom());
System.out.println("Total in all room is "+PeopleInRooms.getNumberPeopleInAllRooms());
b.removeOneFromRoom();
b.removeOneFromRoom();
a.removeOneFromRoom();
a.removeOneFromRoom();
System.out.println("Total in all room is "+PeopleInRooms.getNumberPeopleInAllRooms());
a.removeOneFromRoom();
a.removeOneFromRoom();
System.out.println("Room A holds "+a.getNumberPeopleInRoom());
System.out.println("Room B holds "+b.getNumberPeopleInRoom());
System.out.println("Total in all room is "+PeopleInRooms.getNumberPeopleInAllRooms());
}
}
/*
Output:
Room A holds 2
Room B holds 3
Total in all room is 5
Total in all room is 1
Room A holds 0
Room B holds 1
Total in all room is 1
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.