Feeder Class Simulation
AP CSA FRQ Tester: Feeder Class Simulation (2024)
This notebook allows you to test your implementation of the simulateOneDay
and simulateManyDays
methods for the Feeder class.
The test harness will:
- Append your code to a predefined test structure.
- Run several test cases.
- Display the results of the test cases.
Instructions
- Add the code as per the FRQ instructions in the //YOUR CODE HERE
-
Run both code cells to test your code for errors against provided test cases
// Your Implementation
import java.util.Random;
public class Feeder {
public int currentFood; // Amount of food in grams in the feeder
public Feeder(int initialFood) {
currentFood = initialFood;
}
/**
* Simulates one day with numBirds birds or possibly a bear at the feeder.
* Precondition: numBirds > 0
*/
public void simulateOneDay(int numBirds) {
double chance = Math.random();
Random random = new Random();
if(chance <= 0.95)
{
int foodPerBird = random.nextInt((50-10)+1)+10;
currentFood -= numBirds*foodPerBird;
if(currentFood <0)
{
currentFood = 0;
}
}
else
{
currentFood = 0;
}
}
/**
* Simulates numDays of activity at the feeder with numBirds birds.
* Returns the number of days on which food was found in the feeder.
* Precondition: numBirds > 0, numDays > 0
*/
public int simulateManyDays(int numBirds, int numDays) {
int foodFound = 0;
while(numDays > 0 && currentFood > 0)
{
numDays--;
foodFound++;
simulateOneDay(numBirds);
}
return foodFound;
}
}
import java.util.Random;
public class FeederTest {
public static void main(String[] args) {
StringBuilder results = new StringBuilder();
// Test Case 1
Feeder feeder1 = new Feeder(2400);
feeder1.simulateOneDay(10);
results.append("Test Case 1: Current food after one day: ").append(feeder1.currentFood).append("\n");
// Test Case 2
Feeder feeder2 = new Feeder(250);
int daysWithFood2 = feeder2.simulateManyDays(10, 5);
results.append("Test Case 2: Days with food: ").append(daysWithFood2)
.append(", Remaining food: ").append(feeder2.currentFood).append("\n");
// Test Case 3
Feeder feeder3 = new Feeder(0);
int daysWithFood3 = feeder3.simulateManyDays(5, 10);
results.append("Test Case 3: Days with food: ").append(daysWithFood3)
.append(", Remaining food: ").append(feeder3.currentFood).append("\n");
// Print Results
System.out.println(results.toString());
}
}
// Run the Test Harness
FeederTest.main(null);
Test Case 1: Current food after one day: 2250
Test Case 2: Days with food: 1, Remaining food: 0
Test Case 3: Days with food: 0, Remaining food: 0