• Suppose that you are going to create an object used to count the number of peo
ID: 3757864 • Letter: #
Question
• Suppose that you are going to create an object used to count the number of people in a room. We know that the number of people in the room can never be negative.
– Create a RoomCounter class having three public methods:
• addPerson—adds one person to the room
• removePerson—removes one person from the room
• getCount —returns the number of people in the room
– If removePerson would make the number of people less than zero, throw a NegativeCounterException.
– Finish the program.....
import java.util.Scanner;
public class RoomCounter {
private int count;
public RoomCounter() { //constructor: creates a new instance of RoomCounter
count = 0;
}
public void addPerson(){ // Accessors and Mutators
count++;
}
public void removePerson() throws NegativeCounterException{ / / write removePerson method
}
public int getCount(){
return count;
}
public static void main(String[] args) {
RoomCounter rc = new RoomCounter();
System.out.println("The constructor should give us an empty room");
System.out.println("The count is " + rc.getCount());
System.out.println("Add three people to the room ");
rc.addPerson(); rc.addPerson(); rc.addPerson();
System.out.println("The count is " + rc.getCount());
// remove two people from the room, show the count
//remove one person from the room, show the count
//remove one more person from the room, show the count
}
Explanation / Answer
public void removePerson() throws NegativeCounterException{
if(count - 1 < 0)
throw new NegativeCounterException();
else
count--;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.