Java Programming Day 7

HimanshiHimanshi
6 min read

Day 7 Java: Arrays, Matrices, 2D Arrays, and Interactive Programs

Today I explored Java arrays in depth, focusing on multidimensional arrays (matrices), character arrays, and interactive programs using arrays with user input. Alongside that, I built a fun Rock-Paper-Scissors game to apply control structures and user interaction.


1. MatrixExample: Printing Two 2D Integer Arrays

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

        // Define 3 arrays representing rows of the first matrix
        int[] num1 = {1, 0, 1};
        int[] num2 = {0, 1, 0};
        int[] num3 = {1, 0, 1};

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

        // Print the first matrix using enhanced for loops
        System.out.println("First matrix:");
        for (int[] row : matrix) {
            for (int cell : row) {
                System.out.print(cell + " ");
            }
            System.out.println();
        }

        System.out.println();

        // Define and print another matrix directly with nested arrays
        int[][] matrix2 = {
            {2, 3, 4},
            {5, 6, 7},
            {8, 9, 10}
        };

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

Notes:

  • Demonstrates how to declare and initialize 2D arrays in two ways: using separate arrays combined into one, and directly inline.

  • Uses nested enhanced for loops to iterate and print matrix elements row-wise.

  • Useful for understanding matrix structures in Java and how to manipulate them.


2. GroceryMatrix: 2D String Array with Modification

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

        // Categories of groceries as arrays
        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) {
            for (String item : category) {
                System.out.print(item + "   ");
            }
            System.out.println();
        }

        // Modify one item in the fruits category
        System.out.println("\nUpdating an item...");
        groceries[0][1] = "Mango"; // Replace Banana with Mango

        // 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();
        }
    }
}

Notes:

  • Illustrates combining multiple related 1D arrays into a 2D array to organize data categorically.

  • Shows how to access and modify elements in a 2D array by row and column indices.

  • Reinforces concepts of arrays as data structures for real-world lists.


3. TelephonePad: 2D Char Array Representing a Phone Keypad

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

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

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

Notes:

  • Uses a 2D char array to represent a physical keypad layout.

  • Perfect example of how arrays can represent grids or matrices of characters.

  • Useful for GUI design or input handling based on layouts.


4. QuizGame: Multiple Choice Quiz with User Input

javaCopyEditimport java.util.Scanner;

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

        Scanner scanner = new Scanner(System.in);

        // Array of 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 of options corresponding to 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 array (option numbers)
        int[] answers = {3, 1, 2, 4, 3};
        int score = 0;

        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 current question
            for (String option : options[i]) {
                System.out.println(option);
            }

            // Get user's guess
            System.out.print("Enter your guess: ");
            int guess = scanner.nextInt();

            // Check answer and give feedback
            if (guess == answers[i]) {
                System.out.println("*********");
                System.out.println("CORRECT!");
                System.out.println("*********");
                score++;
            } else {
                System.out.println("*********");
                System.out.println("  WRONG! ");
                System.out.println("*********");
            }
        }

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

Notes:

  • Shows how to use arrays for storing questions, options, and answers.

  • Implements user input via Scanner and loops through the quiz questions interactively.

  • Introduces basic validation and feedback with conditionals.

  • Great example of combining arrays and control flow to build a console app.


5. RockPaperScissorsGame: Interactive Game with Randomness and User Input

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();
        String[] choices = {"rock", "paper", "scissors"};
        String playAgain = "yes";

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

            // Validate input
            if (!playerChoice.equals("rock") &&
                !playerChoice.equals("paper") &&
                !playerChoice.equals("scissors")) {
                System.out.println("Invalid choice—please try again.");
                continue;
            }

            // Computer move
            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!");
            }

            // Play again prompt
            System.out.print("Play again? (yes/no): ");
            playAgain = scanner.nextLine().trim().toLowerCase();

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

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

Notes:

  • Combines arrays, random number generation, string manipulation, and loops.

  • Demonstrates input validation and clean handling of invalid inputs.

  • Uses do-while loop for repeated gameplay until user quits.

  • A fun, interactive console project practicing conditionals and loops.


Summary of Day 7 Learning

  • 2D arrays and matrices: Learned how to declare, initialize, and iterate through two-dimensional arrays, useful for grids and tables.

  • String arrays for categorical data: Organizing related strings into grouped arrays for structured data management.

  • Character arrays: Representing and printing character-based grids (e.g., telephone keypad).

  • Interactive user input: Implementing quizzes and games by accepting user responses with validation.

  • Randomness and game logic: Using Random class to simulate unpredictable computer choices and coding win/loss conditions.

  • Loop control: Using enhanced for loops for easy array traversal and do-while loops for repeated user interaction.

  • Good coding practices: Adding meaningful prompts, clear outputs, and handling invalid inputs gracefully.


Day 7 was a comprehensive dive into arrays, interactivity, and control flow, bridging foundational knowledge with practical applications. I feel more confident building real-world Java programs that can handle data and user interaction dynamically.

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