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() and play()

Your task

Extend the simulation by adding emotion to your pet.

  1. Add a new instance variable called happiness to Pet.

    1. Start it at a reasonable value (for example: 5).

  2. Update the pet’s behavior:

    1. When the pet plays, its happiness should increase.

    2. When the pet becomes too hungry, its happiness should decrease.

  3. Create a helper method that:

    1. Checks the pet’s hunger level

    2. Prints a message if the pet is very hungry and unhappy

  4. Update the output in feed() and play() 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() and play()

Your task

Extend the simulation by adding emotion to your pet.

  1. Add a new instance variable called happiness to Pet.

    1. Start it at a reasonable value (for example: 5).

  2. Update the pet’s behavior:

    1. When the pet plays, its happiness should increase.

    2. When the pet becomes too hungry, its happiness should decrease.

  3. Create a helper method that:

    1. Checks the pet’s hunger level

    2. Prints a message if the pet is very hungry and unhappy

  4. Update the output in feed() and play() 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();
    }
}
Project: Simulate with objects