Java Programming Day 8

HimanshiHimanshi
5 min read

✨ Java Day 8 – Slot Machine Game 🎰 + Car Class πŸš— + Real OOP Concepts πŸ› οΈ


πŸ‘‹ Hey everyone!

Today was hands-down one of the most fun and productive days in my Java learning journey so far! I tackled three very different programs β€” each unlocking new concepts and connecting the dots around Object-Oriented Programming (OOP), game logic, and real-world modeling.

Whether you’re just starting or revisiting Java, these examples will feel relatable and insightful. Let me walk you through everything I coded and learned.


🎰 1. SLOT MACHINE GAME – My First Java Game!

What does it do?

  • You start with a balance of β‚Ή100.

  • You place bets for each spin.

  • Three random symbols (emojis) appear after each spin.

  • Matching symbols win money β€” 3 matches is a jackpot!

  • If no matches, you lose the bet amount.

  • Game continues until you run out of money or quit.

Why this game?

  • It’s a perfect beginner project to practice:

    • Generating random values

    • Handling user input

    • Using loops and conditions

    • Designing simple game logic


Code:

javaCopyEditimport java.util.*;

public class SlotMachine {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random rand = new Random();

        String[] symbols = {"πŸ‡", "🍈", "πŸ‰", "🍊", "πŸ‹"};
        int balance = 100;

        System.out.println("🎰 Welcome to JAVA Slot Machine!");
        System.out.println("Symbols: πŸ‡πŸˆπŸ‰πŸŠπŸ‹");

        while (balance > 0) {
            System.out.println("πŸ’° Current Balance: β‚Ή" + balance);
            System.out.print("Place your bet: ");
            int bet = scanner.nextInt();

            if (bet > balance || bet <= 0) {
                System.out.println("❌ Invalid bet amount!");
                continue;  // Prompt user again without losing balance
            }

            String sym1 = symbols[rand.nextInt(symbols.length)];
            String sym2 = symbols[rand.nextInt(symbols.length)];
            String sym3 = symbols[rand.nextInt(symbols.length)];

            System.out.println("Spinning...");
            System.out.println(sym1 + " | " + sym2 + " | " + sym3);

            if (sym1.equals(sym2) && sym2.equals(sym3)) {
                int winnings = bet * 5;
                balance += winnings;
                System.out.println("πŸŽ‰ Jackpot! You won β‚Ή" + winnings);
            } else if (sym1.equals(sym2) || sym2.equals(sym3)) {
                int winnings = bet * 2;
                balance += winnings;
                System.out.println("😊 Nice! You won β‚Ή" + winnings);
            } else {
                balance -= bet;
                System.out.println("πŸ’” You lost this round.");
            }

            System.out.print("Play again? (yes/no): ");
            String choice = scanner.next();
            if (!choice.equalsIgnoreCase("yes")) {
                break;
            }
        }

        System.out.println("Game over! Final balance: β‚Ή" + balance);
        scanner.close();
    }
}

What I Learned:

  • Random class for generating unpredictable results β€” crucial for game logic.

  • Loops & conditions combined to run the game continuously and check win/loss logic.

  • Validating user input for bets and decisions keeps the game error-free.

  • Using emojis made the console game more engaging!

  • Practiced state management via the balance variable β€” keeping track of money.

  • Thought carefully about how to compare symbols using .equals() method.


πŸš— 2. CAR CLASS – Modeling a Real-World Object in Java

What does this class represent?

  • A Car with attributes:

    • make (manufacturer)

    • model

    • year

    • price

    • isRunning (boolean to track whether the car engine is on)

  • Behavior methods:

    • start()

    • stop()

    • drive()

    • brake()


Code:

javaCopyEditpublic class Car {
    String make = "Toyota";
    String model = "Corolla";
    int year = 2020;
    double price = 1500000.0;
    boolean isRunning = false;  // Tracks if the car is currently running

    void start() {
        isRunning = true;
        System.out.println("πŸš— Car started.");
    }

    void stop() {
        isRunning = false;
        System.out.println("πŸ›‘ Car stopped.");
    }

    void drive() {
        if (isRunning) {
            System.out.println("🏁 Car is driving.");
        } else {
            System.out.println("⚠️ Start the car first!");
        }
    }

    void brake() {
        System.out.println("🚦 Car is braking.");
    }
}

What I Learned:

  • Designing a class that mimics real-world entities β€” thinking of attributes and behaviors.

  • Using a boolean flag (isRunning) to represent an internal state of the object and control behavior.

  • Ensuring methods behave differently based on object state (car can't drive if not started).

  • Reinforced method declaration, field initialization, and printing to console.

  • Understanding how objects hold both data and behavior together.


πŸ› οΈ 3. MAIN CLASS – Putting the Car Object to Work

What does this do?

  • Creates a Car object.

  • Prints its attributes.

  • Calls its methods in order β€” start, drive, brake, stop.

  • Prints the running state before and after actions.


Code:

javaCopyEditpublic class Main {
    public static void main(String[] args) {
        Car car = new Car();

        System.out.println("🚘 Car Details:");
        System.out.println("Make: " + car.make);
        System.out.println("Model: " + car.model);
        System.out.println("Year: " + car.year);
        System.out.println("Price: β‚Ή" + car.price);
        System.out.println("Running Status: " + car.isRunning);

        car.start();
        System.out.println("Running Status: " + car.isRunning);

        car.drive();
        car.brake();
        car.stop();

        System.out.println("Running Status: " + car.isRunning);
    }
}

What I Learned:

  • How to create objects from a class and call their methods using the dot operator ..

  • Visualizing how data (attributes) and behavior (methods) live together in an object.

  • Practiced method sequencing to simulate real-world usage.

  • Became more confident with Java syntax for object creation and interaction.


πŸ“˜ Summary Table: What Java Day 8 Gave Me

ConceptMy Takeaway
Game LogicLearned how to combine loops, random generation, and conditions effectively in a fun project.
OOP BasicsCreated a meaningful class and understood the importance of fields and methods in objects.
State ManagementUsed boolean flags (isRunning) to manage internal object states properly.
Real-Life MappingSaw how Java lets you simulate real-world objects and scenarios (slot machine, car).
User InteractionPracticed input handling and validation using Scanner class.

🫢 Final Thoughts

I’m really proud of Day 8 β€” not because I coded something complex, but because I enjoyed the process and understood how everything works together. Java is not just syntax or theory; it’s a powerful tool to bring ideas and simulations to life.

From now on, I want to keep mixing creativity with code and build things that are both fun and educational.


0
Subscribe to my newsletter

Read articles from Himanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Himanshi
Himanshi

Hi! I'm a curious and self-driven programmer currently pursuing my BCA πŸŽ“ and diving deep into the world of Java β˜• from Day 1. I already have a foundation in programming, and now I'm expanding my skills one concept, one blog, and one project at a time. I’m learning Java through Bro Code’s YouTube tutorials, experimenting with code, and documenting everything I understand β€” from basic syntax to real-world applications β€” to help others who are just starting out too. I believe in learning in public, progress over perfection, and growing with community support. You’ll find beginner-friendly Java breakdowns, hands-on code snippets, and insights from my daily coding grind right here. πŸ’‘ Interests: Java, Web Dev, Frontend Experiments, AI-curiosity, Writing & Sharing Knowledge πŸ› οΈ Tools: Java β€’ HTML/CSS β€’ JavaScript β€’ Python (basics) β€’ SQL 🎯 Goal: To become a confident Full Stack Developer & AI Explorer πŸ“ Based in India | Blogging my dev journey #JavaJourney #100DaysOfCode #CodeNewbie #LearnWithMe