Java Programming Day 7

HimanshiHimanshi
7 min read

🌟 Java Day 7 – Mastering Arrays, Matrices, and Interactive Programs 🎯


Hey there! 👋

Today, I dove deep into Java arrays, especially multidimensional arrays (matrices), and explored how to use arrays in real interactive programs. I also coded some fun projects like a quiz game and a Rock-Paper-Scissors game to apply what I learned about control flow and user input.

Let me take you through everything step-by-step!


1️⃣ MatrixExample: Printing Two 2D Integer Arrays

What I did:

  • Created 2D integer arrays (matrices) using two different approaches:

    • First by combining separate 1D arrays

    • Then directly declaring a nested 2D array inline

  • Printed the matrices neatly using nested enhanced for loops

Code with comments:

javaCopyEditpublic class MatrixExample {
    public static void main(String[] args) {

        // Define individual rows as 1D arrays
        int[] num1 = {1, 0, 1};
        int[] num2 = {0, 1, 0};
        int[] num3 = {1, 0, 1};

        // Combine these rows into a 2D array (matrix)
        int[][] matrix = {num1, num2, num3};

        // Print the first matrix
        System.out.println("First matrix:");
        for (int[] row : matrix) {          // Loop over each row
            for (int cell : row) {          // Loop over each element in the row
                System.out.print(cell + " "); // Print the cell followed by space
            }
            System.out.println();            // New line after each row
        }

        System.out.println(); // Blank line for separation

        // Declare and initialize a 2D array directly (inline)
        int[][] matrix2 = {
            {2, 3, 4},
            {5, 6, 7},
            {8, 9, 10}
        };

        // Print the second matrix
        System.out.println("Second matrix:");
        for (int[] row : matrix2) {
            for (int cell : row) {
                System.out.print(cell + " ");
            }
            System.out.println();
        }
    }
}

What I learned:

  • Two ways to create 2D arrays: composing from 1D arrays or declaring them inline.

  • Using nested enhanced for loops simplifies traversing rows and columns.

  • Understanding this helps with applications like image grids, chess boards, or other matrix-like data.


2️⃣ GroceryMatrix: Organizing Grocery Items with 2D String Arrays

What I did:

  • Created separate string arrays for fruits, vegetables, and meats

  • Grouped them into a 2D array to organize categories

  • Printed the original list

  • Updated one element and printed the updated list

Code with comments:

javaCopyEditpublic class GroceryMatrix {
    public static void main(String[] args) {

        // Define separate arrays for each grocery category
        String[] fruits = {"Apple", "Banana", "Orange"};
        String[] vegetables = {"Carrot", "Broccoli", "Spinach"};
        String[] meats = {"Chicken", "Beef", "Pork"};

        // Combine categories into a 2D array
        String[][] groceries = {fruits, vegetables, meats};

        // Print original groceries list
        System.out.println("Original groceries list:\n");
        for (String[] category : groceries) {      // Loop over each category
            for (String item : category) {          // Loop over each item
                System.out.print(item + "   ");
            }
            System.out.println();                    // New line after each category
        }

        // Modify one item in the fruits category (Banana → Mango)
        System.out.println("\nUpdating an item...");
        groceries[0][1] = "Mango"; // Access 0th row (fruits), 1st element (Banana)

        // Print updated groceries list
        System.out.println("\nUpdated groceries list:\n");
        for (String[] category : groceries) {
            for (String item : category) {
                System.out.print(item + "   ");
            }
            System.out.println();
        }
    }
}

What I learned:

  • 2D arrays can represent categorized data clearly.

  • You can access and modify elements by specifying row and column indices.

  • This is great for managing real-world lists programmatically.


3️⃣ TelephonePad: Representing a Phone Keypad with a 2D Char Array

What I did:

  • Created a 2D char array representing the phone keypad layout

  • Printed the keypad to look like the actual button layout

Code with comments:

javaCopyEditpublic class TelephonePad {
    public static void main(String[] args) {

        // Define a 2D char array simulating a phone keypad
        char[][] telephone = {
            {'1', '2', '3'},
            {'4', '5', '6'},
            {'7', '8', '9'},
            {'*', '0', '#'}
        };

        // Print each row of the keypad
        for (char[] row : telephone) {     // Loop over rows
            for (char number : row) {      // Loop over each character
                System.out.print(number + " ");
            }
            System.out.println();          // New line after each row
        }
    }
}

What I learned:

  • 2D char arrays are perfect for representing grids or layouts of characters.

  • This concept can be expanded to game boards, UI grids, or input layouts.


4️⃣ QuizGame: Multiple Choice Quiz with User Input and Scoring

What I did:

  • Stored questions and options in arrays

  • Took user input with Scanner

  • Checked user’s answers against correct options

  • Tracked and displayed score at the end

Code with comments:

javaCopyEditimport java.util.Scanner;

public class QuizGame {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Array of quiz questions
        String[] questions = {
            "What is the main function of a router?",
            "What part of the computer is considered the brain?",
            "What year was Facebook launched?",
            "Who is known as the father of computer?",
            "What was the first programming language?"
        };

        // 2D array holding options for each question
        String[][] options = {
            {"1. Storing files", "2. Encrypting data", "3. Directing internet traffic", "4. Managing passwords"},
            {"1. CPU", "2. Hard Drive", "3. RAM", "4. GPU"},
            {"1. 2000", "2. 2004", "3. 2006", "4. 2008"},
            {"1. Steve Jobs", "2. Bill Gates", "3. Alan Turing", "4. Charles Babbage"},
            {"1. COBOL", "2. C", "3. Fortran", "4. Assembly"}
        };

        // Correct answers (option numbers)
        int[] answers = {3, 1, 2, 4, 3};

        int score = 0; // Initialize score

        System.out.println("******************************");
        System.out.println("Welcome to the Java Quiz Game!");
        System.out.println("******************************");

        // Loop through all questions
        for (int i = 0; i < questions.length; i++) {
            System.out.println(questions[i]);

            // Print options for the current question
            for (String option : options[i]) {
                System.out.println(option);
            }

            System.out.print("Enter your guess (1-4): ");
            int guess = scanner.nextInt();

            // Check if the guess is correct
            if (guess == answers[i]) {
                System.out.println("*********");
                System.out.println("CORRECT!");
                System.out.println("*********");
                score++; // Increment score
            } else {
                System.out.println("*********");
                System.out.println("  WRONG! ");
                System.out.println("*********");
            }
            System.out.println();
        }

        // Show final score
        System.out.println("Your Final Score is: " + score + " out of " + questions.length);

        scanner.close();
    }
}

What I learned:

  • Using arrays to store questions, multiple options, and answers efficiently.

  • Taking user input and checking answers with conditional statements.

  • Providing immediate feedback and scoring system.

  • Combining arrays and control flow to build interactive console applications.


5️⃣ RockPaperScissorsGame: Interactive Game with Randomness and Input Validation

What I did:

  • Asked user to input “rock,” “paper,” or “scissors”

  • Generated random computer choice using Random class

  • Compared choices to determine the winner

  • Used a loop to repeat until user decides to quit

  • Validated user input to handle mistakes gracefully

Code with comments:

javaCopyEditimport java.util.Scanner;
import java.util.Random;

public class RockPaperScissorsGame {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        // Possible choices for the game
        String[] choices = {"rock", "paper", "scissors"};

        String playAgain = "yes"; // Control variable for looping

        do {
            System.out.print("Enter your move (rock, paper, scissors): ");
            String playerChoice = scanner.nextLine().trim().toLowerCase();

            // Input validation: check if player input is valid
            if (!playerChoice.equals("rock") &&
                !playerChoice.equals("paper") &&
                !playerChoice.equals("scissors")) {
                System.out.println("Invalid choice—please try again.");
                continue; // Restart loop if input invalid
            }

            // Generate computer choice randomly
            String computerChoice = choices[random.nextInt(3)];
            System.out.println("Computer choice: " + computerChoice);

            // Determine winner
            if (playerChoice.equals(computerChoice)) {
                System.out.println("It's a tie!");
            } else if ((playerChoice.equals("rock") && computerChoice.equals("scissors")) ||
                       (playerChoice.equals("paper") && computerChoice.equals("rock")) ||
                       (playerChoice.equals("scissors") && computerChoice.equals("paper"))) {
                System.out.println("You win!");
            } else {
                System.out.println("Computer wins!");
            }

            // Ask if the user wants to play again
            System.out.print("Play again? (yes/no): ");
            playAgain = scanner.nextLine().trim().toLowerCase();

        } while (playAgain.equals("yes"));

        System.out.println("Thanks for playing!");
        scanner.close();
    }
}

What I learned:

  • How to combine arrays, randomness, and user input for an engaging game.

  • Validating user input and handling invalid entries smoothly with continue.

  • Using a do-while loop to enable repeated gameplay until the user quits.

  • Solid practice with conditionals and string manipulation.


📚 Summary of Day 7 Learning

TopicWhat I Learned & Practiced
2D Arrays & MatricesDeclaring, initializing, and looping through 2D arrays for matrix-like data representation.
Categorizing DataOrganizing related strings into 2D arrays for easy management and modification.
Character GridsUsing 2D char arrays to represent keypad layouts or similar grid structures.
User InteractionImplementing quizzes and games that take input, check answers, and provide feedback dynamically.
Randomness & Game LogicSimulating unpredictability and coding game rules using conditionals.
Looping TechniquesEnhanced for loops for array traversal, and do-while loops for repeated user interactions.
Good Coding PracticesClear instructions/prompts, validation, and user-friendly outputs for smoother experience.

🎉 Final Thoughts

Today was a rewarding and engaging dive into arrays and interactive programming. The mix of data structures and user input handling helped me connect theory to practical, fun projects!

I’m excited to build even more complex apps using these foundations!

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