Challenge: Simulate with Objects
You’re building a simple simulation using an object that remembers its state and changes over time.
A Pet class is already set up with:
a name
a hunger level
actions to
feed()andplay()
Your task
Extend the simulation by adding emotion to your pet.
Add a new instance variable called
happinesstoPet.Start it at a reasonable value (for example:
5).
Update the pet’s behavior:
When the pet plays, its happiness should increase.
When the pet becomes too hungry, its happiness should decrease.
Create a helper method that:
Checks the pet’s hunger level
Prints a message if the pet is very hungry and unhappy
Update the output in
feed()andplay()so it shows both hunger and happiness.
Goal
By the end, your pet should:
Remember multiple pieces of state
Change over time based on actions
React differently depending on its condition
Challenge: Simulate with Objects
You’re building a simple simulation using an object that remembers its state and changes over time.
A Pet class is already set up with:
a name
a hunger level
actions to
feed()andplay()
Your task
Extend the simulation by adding emotion to your pet.
Add a new instance variable called
happinesstoPet.Start it at a reasonable value (for example:
5).
Update the pet’s behavior:
When the pet plays, its happiness should increase.
When the pet becomes too hungry, its happiness should decrease.
Create a helper method that:
Checks the pet’s hunger level
Prints a message if the pet is very hungry and unhappy
Update the output in
feed()andplay()so it shows both hunger and happiness.
Goal
By the end, your pet should:
Remember multiple pieces of state
Change over time based on actions
React differently depending on its condition
import java.util.Scanner;
public class Main {
static class Pet {
String name;
int hunger = 5;
public Pet(String name) {
this.name = name;
}
public void feed() {
hunger--;
System.out.println(name + " is fed. Hunger: " + hunger);
}
public void play() {
hunger++;
System.out.println(name + " played. Hunger: " + hunger);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Pet pet = new Pet("Milo");
int choice = 0;
while (choice != 3) {
System.out.println("\n1. Feed\n2. Play\n3. Exit\n> ");
choice = input.nextInt();
if (choice == 1) pet.feed();
else if (choice == 2) pet.play();
}
System.out.println("Goodbye!");
input.close();
}
}