Java Programming Day 4

HimanshiHimanshi
7 min read

Java Conditionals, Logical Operators & Loops — Detailed Practice and Programs

1. Logical Operators with User Input

javaCopyEditimport java.util.Scanner;

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

        System.out.print("Enter the temperature: ");
        double temp = scanner.nextDouble();

        System.out.print("Is it sunny? (true/false): ");
        boolean isSunny = scanner.nextBoolean();

        if (temp <= 30 && temp >= 0 && isSunny) {
            System.out.println("The weather is good.");
            System.out.println("It is Sunny outside.");
        } else if (temp <= 30 && temp >= 0 && !isSunny) {
            System.out.println("The weather is good.");
            System.out.println("It is Cloudy outside.");
        } else if (temp > 30 || temp < 0) {
            System.out.println("The weather is bad.");
        }

        scanner.close();
    }
}

Notes:

  • Logical AND (&&): Both conditions must be true to enter that block.

  • Logical OR (||): At least one condition must be true.

  • Logical NOT (!): Reverses the boolean value (true to false, false to true).

  • Program checks temperature range (0-30°C) and if it is sunny.

  • Prints appropriate messages based on combined conditions.

  • Using scanner.nextDouble() and scanner.nextBoolean() to take user inputs for dynamic interaction.


2. Username Validation

javaCopyEditimport java.util.Scanner;

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

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

        if (username.length() < 4 || username.length() > 12) {
            System.out.println("Username must be between 4-12 characters.");
        } else if (username.contains(" ") || username.contains("_")) {
            System.out.println("Username must not contain any whitespaces or underscores.");
        } else {
            System.out.println("WELCOME " + username);
        }

        scanner.close();
    }
}

Notes:

  • .length() returns the string length.

  • .contains() checks if a string contains a certain substring.

  • Logical OR (||) combines conditions for invalid usernames.

  • Valid username must be 4–12 characters, no spaces or underscores.

  • Simple input validation example.


3. While Loop Waiting for Name Input

javaCopyEditimport java.util.Scanner;

public class NamePromptWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = "";

        while (name.isEmpty()) {
            System.out.print("Enter your name: ");
            name = scanner.nextLine();
        }

        System.out.println("Hello " + name);

        scanner.close();
    }
}

Notes:

  • while loop runs as long as the condition is true.

  • .isEmpty() returns true if the string length is 0.

  • Ensures user cannot proceed without entering a non-empty name.

  • Demonstrates input validation using loops.


4. While Loop for Game Quit Input

javaCopyEditimport java.util.Scanner;

public class GameQuitLoop {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String response = "";

        while (!response.equals("Q")) {
            System.out.print("You are in a Game!! Press Q to quit: ");
            response = scanner.nextLine().toUpperCase();
        }

        System.out.println("You have exited the game!!");

        scanner.close();
    }
}

Notes:

  • Loop continues until user inputs 'Q' (case-insensitive).

  • .toUpperCase() normalizes input to uppercase for easier comparison.

  • Example of a user-controlled exit condition.

  • Useful for menu-driven programs or interactive loops.


5. Age Input Validation (While Loop)

javaCopyEditimport java.util.Scanner;

public class AgeValidationWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age;

        System.out.print("Enter your age: ");
        age = scanner.nextInt();

        while (age < 0) {
            System.out.print("Your age can't be negative!!! Enter your age again: ");
            age = scanner.nextInt();
        }

        System.out.println("You are " + age + " years old.");

        scanner.close();
    }
}

Notes:

  • Loop repeats while age is invalid (negative).

  • Demonstrates defensive programming to ensure valid inputs.

  • Uses scanner.nextInt() to get integer inputs.


6. Age Input Validation (Do-While Loop)

javaCopyEditimport java.util.Scanner;

public class AgeValidationDoWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age;

        do {
            System.out.print("Enter your age: ");
            age = scanner.nextInt();
            if (age < 0) {
                System.out.println("Your age can't be negative!!!");
            }
        } while (age < 0);

        System.out.println("You are " + age + " years old.");

        scanner.close();
    }
}

Notes:

  • do-while executes body at least once before checking condition.

  • Useful when input is mandatory but needs validation.

  • Same validation goal as previous but different loop structure.


7. Number Input Validation (While Loop)

javaCopyEditimport java.util.Scanner;

public class NumberRangeWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number = 0;

        while (number < 1 || number > 10) {
            System.out.print("Enter a number between 1-10: ");
            number = scanner.nextInt();
        }

        System.out.println("You hit " + number);

        scanner.close();
    }
}

Notes:

  • User must enter number between 1 and 10.

  • Loop continues until valid input is provided.

  • Demonstrates OR condition for range checking.


8. Number Input Validation (Do-While Loop)

javaCopyEditimport java.util.Scanner;

public class NumberRangeDoWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number;

        do {
            System.out.print("Enter a number between 1-10: ");
            number = scanner.nextInt();
        } while (number < 1 || number > 10);

        System.out.println("You picked " + number);

        scanner.close();
    }
}

Notes:

  • Same validation as previous, but ensures prompt shows at least once.

  • Useful for forced user input scenarios.


9. Number Guessing Game

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

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

        int guess;
        int attempts = 0;
        int min = 1;
        int max = 100;
        int randomNumber = random.nextInt(min, max + 1);

        System.out.println("Welcome to the Number Guessing Game!");
        System.out.printf("Guess a number between %d - %d:\n", min, max);

        do {
            System.out.print("Enter a guess: ");
            guess = scanner.nextInt();
            attempts++;

            if (guess < randomNumber) {
                System.out.println("Too low! Try again.");
            } else if (guess > randomNumber) {
                System.out.println("Too high! Try again.");
            } else {
                System.out.println("Correct!!! The number was " + randomNumber);
                System.out.println("Number of attempts: " + attempts);
            }
        } while (guess != randomNumber);

        System.out.println("Congratulations!!! You guessed the right number!!!");

        scanner.close();
    }
}

Notes:

  • Uses Random class to generate a random number.

  • do-while loop keeps the game running until the correct guess.

  • Feedback helps guide the player closer to the answer.

  • attempts variable counts how many tries user took.


10. For Loop Counting Up

javaCopyEditimport java.util.Scanner;

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

        System.out.print("Enter how many times you want to loop: ");
        int max = scanner.nextInt();

        for (int i = 1; i <= max; i++) {
            System.out.println(i);
        }

        scanner.close();
    }
}

Notes:

  • for loop repeats a fixed number of times.

  • The loop variable i starts at 1 and increments by 1 each time.

  • Loop ends after max iterations.


11. Countdown Timer

javaCopyEditimport java.util.Scanner;

public class CountdownTimer {
    public static void main(String[] args) throws InterruptedException {
        Scanner scanner = new Scanner(System.in);

        System.out.print("How many seconds to countdown from?: ");
        int start = scanner.nextInt();

        for (int i = start; i >= 0; i--) {
            System.out.println(i);
            Thread.sleep(1000);
        }
        System.out.println("Happy New Year!!");

        scanner.close();
    }
}

Notes:

  • Counts down from user input to zero.

  • Thread.sleep(1000) pauses execution for 1 second.

  • throws InterruptedException needed because sleep can be interrupted.

  • Useful for simple timer functionality.


12. Break vs Continue

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

        System.out.println("Using break:");
        for (int i = 0; i <= 10; i++) {
            if (i == 5) {
                break;
            }
            System.out.print(i + " ");
        }
        System.out.println("\n");

        System.out.println("Using continue:");
        for (int j = 0; j <= 10; j++) {
            if (j == 5) {
                continue;
            }
            System.out.print(j + " ");
        }
    }
}

Notes:

  • break exits the entire loop immediately.

  • continue skips current iteration and moves to next loop iteration.

  • Helps control loop flow based on conditions.


13. Nested Loops Simple Print

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

        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 9; j++) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
}

Notes:

  • Outer loop controls rows.

  • Inner loop controls columns.

  • Prints the outer loop variable repeatedly on each row.


14. Nested Loops with User Input to Print Grid of Symbols

javaCopyEditimport java.util.Scanner;

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

        System.out.print("Enter the number of rows: ");
        int rows = scanner.nextInt();

        System.out.print("Enter the number of columns: ");
        int columns = scanner.nextInt();

        System.out.print("Enter the symbol: ");
        char symbol = scanner.next().charAt(0);

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= columns; j++) {
                System.out.print(symbol);
            }
            System.out.println();
        }

        scanner.close();
    }
}

Notes:

  • User inputs number of rows and columns.

  • Prints a grid with the user’s chosen symbol.

  • Combines nested loops and character printing.


Summary

Today’s exercises focused on:

  • Logical operators and complex if-conditions.

  • Input validation using loops.

  • Mastering while, do-while, and for loops.

  • Control flow modifiers: break and continue.

  • Nested loops to build patterns and grids.

  • Combining input, loops, and output for interactive programs.

These are the building blocks of effective Java programming and will help you create robust, user-friendly applications.

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