Java Programming Day 13

HimanshiHimanshi
6 min read

🚀 Day 13 Java Progress — Revision with Practical Tasks

On Day 13 of my Java learning journey, I focused on revision by practicing various small tasks across concepts I’ve covered so far. I actively engaged with ChatGPT to get specific programming challenges based on core Java fundamentals. This approach helped me reinforce my understanding of user input, arrays, loops, formatted output, and basic control flow.

Here’s a detailed walkthrough of the tasks I completed today, including full programs and simple explanations.

Task 1: Personal Info Printer

Program Explanation

This program collects the user’s personal information such as their name, college, and hobby. It demonstrates how to take string inputs and display them neatly using formatted output.

javaCopyEditimport java.util.Scanner;

public class PersonalInfoPrinter {
    public static void main(String[] args) {
        System.out.println("=== Task 1: Personal Info Printer Started ===");

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine().trim();

        System.out.print("Enter your college name: ");
        String college = scanner.nextLine().trim();

        System.out.print("What's your hobby: ");
        String favoriteHobby = scanner.nextLine().trim();

        System.out.printf("Hello %s, nice to meet you!%n", name);
        System.out.printf("You study in %s%n", college);
        System.out.printf("Your favorite hobby is: %s%n", favoriteHobby);

        scanner.close();

        System.out.println("=== Task 1: Personal Info Printer Completed ===");
    }
}

Detailed Notes

  • Scanner Usage: Created a Scanner object to read input from the user.

  • String Input: Used nextLine() to read full lines (names and hobbies).

  • Trimming Input: .trim() removes leading/trailing spaces for cleaner data.

  • Formatted Output: System.out.printf() used for readable and formatted messages.

  • Resource Management: Closed Scanner to prevent resource leaks.

  • Program Flow: Sequentially asked for inputs and displayed output immediately after.

Key Takeaways

  • How to handle multiple string inputs from users.

  • Importance of formatting output for readability.

  • Proper resource handling by closing the Scanner.


Task 2: Simple Calculator

Program Explanation

This program performs basic arithmetic operations (+, -, *, /) on two numbers based on user input. It uses a switch statement to select the operation and handles division by zero carefully.

javaCopyEditimport java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args) {
        System.out.println("=== Task 2: Simple Calculator Started ===");

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the first number: ");
        double num1 = scanner.nextDouble();

        System.out.print("Enter the second number: ");
        double num2 = scanner.nextDouble();

        System.out.print("Enter the operation you want to perform (+, -, *, /): ");
        char operation = scanner.next().charAt(0);

        double result;

        switch (operation) {
            case '+':
                result = num1 + num2;
                System.out.printf("%.2f + %.2f = %.2f%n", num1, num2, result);
                break;
            case '-':
                result = num1 - num2;
                System.out.printf("%.2f - %.2f = %.2f%n", num1, num2, result);
                break;
            case '*':
                result = num1 * num2;
                System.out.printf("%.2f * %.2f = %.2f%n", num1, num2, result);
                break;
            case '/':
                if (num2 == 0) {
                    System.out.println("Error: Division by zero is not allowed.");
                } else {
                    result = num1 / num2;
                    System.out.printf("%.2f / %.2f = %.2f%n", num1, num2, result);
                }
                break;
            default:
                System.out.println("Invalid operation. Please use +, -, *, or /.");
        }

        scanner.close();

        System.out.println("=== Task 2: Simple Calculator Completed ===");
    }
}

Detailed Notes

  • User Input: Took two double numbers and an operation character.

  • Switch Statement: Chose the operation type with switch for clean code.

  • Arithmetic Operations: Performed addition, subtraction, multiplication, and division.

  • Division Check: Added a condition to prevent division by zero errors.

  • Formatted Printing: Output includes numbers formatted to 2 decimal places.

  • Input Validation: Warns user if the operation is invalid.

  • Scanner Management: Properly closes the scanner after input.

Key Takeaways

  • How to perform conditional logic based on user input.

  • Managing edge cases (like division by zero).

  • Using switch for multi-way branching.

  • Importance of formatted output for numerical results.


Task 3: Number Guessing Game

Program Explanation

This is an interactive game where the computer randomly selects a number between 0 and 100, and the user tries to guess it. After each guess, the program gives hints whether the guess was too high or too low.

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

public class NumberGuessingGame {
    public static void main(String[] args) {
        System.out.println("=== Number Guessing Game Started ===");

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

        int secretNumber = random.nextInt(101);
        int attempts = 0;
        int guess;

        System.out.println("Welcome to the guessing number game!!");

        while (true) {
            System.out.print("Enter your guess (0-100): ");
            guess = scanner.nextInt();
            attempts++;

            if (guess == secretNumber) {
                System.out.println("You guessed the right number!");
                System.out.println("Total attempts: " + attempts);
                break;
            } else if (guess > secretNumber) {
                System.out.println("Too high");
            } else {
                System.out.println("Too low");
            }
        }

        scanner.close();
        System.out.println("=== Number Guessing Game Ended ===");
    }
}

Detailed Notes

  • Random Number: Used Random.nextInt(101) to generate a number from 0 to 100.

  • Looping: Used an infinite while (true) loop until the correct guess is made.

  • Input and Feedback: User inputs guesses; program provides feedback (“Too high”, “Too low”).

  • Attempt Counter: Counts how many guesses the user took.

  • Exit Condition: Loop breaks when the correct guess is found.

  • Resource Management: Closes the scanner at the end.

Key Takeaways

  • Generating random numbers for interactive applications.

  • Designing loops with a clear exit condition.

  • Providing user feedback for a better experience.

  • Tracking attempts or user actions.


Task 4: Shopping Receipt Generator

Program Explanation

This program simulates a simple shopping receipt generator. It takes the number of items, then asks for each item's name and price. Finally, it prints a formatted receipt with a total price.

javaCopyEditimport java.util.Scanner;

public class ShoppingReceipt {
    public static void main(String[] args) {
        System.out.println("=== Task 4: Shopping Receipt Generator Started ===");

        Scanner scanner = new Scanner(System.in);

        System.out.print("How many items are you buying? ");
        int count = scanner.nextInt();
        scanner.nextLine();  // Consume newline

        String[] items = new String[count];
        double[] prices = new double[count];
        double total = 0;

        for (int i = 0; i < count; i++) {
            System.out.printf("Enter name of item %d: ", i + 1);
            items[i] = scanner.nextLine();

            System.out.printf("Enter price of %s: $", items[i]);
            prices[i] = scanner.nextDouble();
            scanner.nextLine();

            total += prices[i];
        }

        System.out.println("\n🧾 Your Receipt:");
        System.out.println("----------------------------");
        for (int i = 0; i < count; i++) {
            System.out.printf("%-20s $%.2f%n", items[i], prices[i]);
        }
        System.out.println("----------------------------");
        System.out.printf("TOTAL:              $%.2f%n", total);

        scanner.close();
        System.out.println("=== Task 4: Shopping Receipt Generator Completed ===");
    }
}

Detailed Notes

  • Arrays: Used arrays to store item names and prices.

  • Loops: Iterated over arrays to input and display data.

  • Formatted Output: Used printf with field width (%-20s) for aligned receipt printing.

  • Accumulating Total: Kept running total while inputting prices.

  • Input Buffer Handling: Called scanner.nextLine() after numeric input to consume newline characters.

  • Clean UI: Clear prompts and separator lines for receipt clarity.

  • Closing Scanner: Resource properly released.

Key Takeaways

  • Managing multiple related inputs with arrays.

  • Aligning text output in console apps.

  • Handling input buffering quirks in Java.

  • Combining loops and arrays for structured data input/output.


Final Summary & Key Learnings

  • User Input Mastery: Confidently handled strings, numbers, and characters using Scanner.

  • Control Flow Skills: Used if-else, switch, and loops effectively.

  • Formatted Output: Applied printf for clear and professional console outputs.

  • Arrays & Data Storage: Used arrays to store and manage multiple values.

  • Random Numbers & Games: Implemented simple interaction with randomization.

  • Resource Management: Learned to properly close input resources.

Day 13’s revision strengthened my foundational Java skills by combining theoretical knowledge with practical coding challenges. The hands-on practice helped me internalize concepts and prepared me for more advanced programming.

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