09 Java Fundamentals | While Loop in Java | By Dummy for Dummies

 

INTRODUCTION

What happened when you were a child and asked your parents for snacks and they refused? You just walked away saying "Yeah snacks are not good for health I should start eating more vegetables". HELL NAH! You cried and begged for snack until they gave up and provided what you asked for.
You kept on repeating until they gave you what you wanted. It was like you were on loop and only one thing could exit that loop. 

In programming we will do the same, we will do some magic and the program will keep on repeating same part of code until we achieve our target. This is called loop in programming

WHILE LOOP

Just as the name suggests, it will execute a part of code while a condition is true. When the condition ia disturbed the loop will stop. Let's simulate a crying baby...
import java.util.Scanner;

public class BabyCandy {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String pocket = "";

        while (!pocket.equals("candy")) {  
            System.out.println("Baby is crying");
            System.out.println("Baby is asking for candy");
            System.out.print("Give something: ");
            pocket = sc.nextLine();
        } 
        
        System.out.println("Baby got candy");
        System.out.println("Baby is happy!");
        
    }
}

OUTPUT:
Baby is crying Baby is asking for candy Give something: toy Baby is crying Baby is asking for candy Give something: chocolate Baby is crying Baby is asking for candy Give something: candy Baby got candy Baby is happy


Explanation

⦿  pocket.equals("candy")  checks if content in pocket is "candy" or not. 

⦿ String does not work on == like others, why is that? we will talk about it later. Therefore we use  .equals() 

⦿ Here we used NOT operator i.e.  !  So the condition actually checks if pocket DOES NOT contain candy, then run the loop.

⦿ All content inside golden curly brackets  {}  will be repeated again and again, until the user enters  candy 

⦿ Kids want what they want, without giving candy the loop will run no matter whatever you give him

⦿ Once you give candy, loop will break, and program will print:
                                Baby got candy 
                                Baby is happy!   

⦿ So this is how the loop goes:
        check pocket → not candy → baby cries → you give something → loop again  
        check pocket → candy → loop ends → baby happy



POINTS TO REMEMBER

⦿ Condition will be checked first, if it is true the loop will start
⦿ Code inside will run and will check condition again before restart
⦿ If you change the condition it'll stop. If you don't it'll continue
⦿ You must code a way to change condition inside the loop or it'll run infinitely
⦿ Here is a demonstration of infinite loop:
public class Main { 
    public static void main(String[] args) {

        int n = 0;

        while (n == 0) { 
            System.out.println("HELP I AM STUCK IN LOOP!"); 
        } 

        System.out.println("Loop exited"); 
    } 
}

OUTPUT:
HELP I AM STUCK IN LOOP! HELP I AM STUCK IN LOOP! HELP I AM STUCK IN LOOP! HELP I AM STUCK IN LOOP! ... 


Here the code will check if n equals 0, every time it'll find the condition true. With no change from inside it'll spam  HELP I AM STUCK IN LOOP  until you close the console manually.
It'll NEVER reach the  Loop exited .



DO WHILE LOOP

Do while loop is a variant of original while loop. There is just a small difference between them.
While Loop: It first checks condition, if it is true then it runs. If condition is not true it will never run the content of loop
Do While Loop: It will execute the code inside loop for once, then check condition if it's true it'll re-run the loop code. If it is not true it won't re-run. But it will always run the loop code at least for once. 
Here is a demonstration:
public class Main { 
    public static void main(String[] args) {
        int number = 1; 

        do { 
            System.out.println("Number: " + number);
            number++;  // increments the number 
        } while (number < 6);  // semicolon required here!

        System.out.println("Loop exited!"); 
    } 
}

OUTPUT:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Loop exited! 


⦿ This code has condition that "While number is less than 6, go back and re-run the loop".
⦿ When the code inside runs, it prints the number, then increase it by one, then check condition again.
⦿ The first output will be given always, then everytime it'll check condition and execute as it allows. 
Note: The while part in the do-while loop ends with semi colon  while(number<6);  

Do while loop  is just a variation of  while loop . You can use any of them depending on your taste and choice, sometimes one is more suitable than other but you still you can use anyone for your tasks.


EXERCISE

Let's do an exercise for what we studied in this post. Study this code, break it down, analyze it and identify the concepts used here. It would be even better if you write down your observations and make a mini report on it.

import java.util.Scanner;


public class WhileLoopExercise {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);


        String secretPin = "1234";   // the correct pin

        String enteredPin = "";      // what the user types

        int attempts = 0;            // counter for attempts

        int maxAttempts = 3;         // maximum chances

        int balance = 1000;          // starting balance


        // while loop to check PIN

        while (!enteredPin.equals(secretPin) && attempts < maxAttempts) {

            System.out.print("Enter your secret PIN: ");

            enteredPin = sc.nextLine();

            attempts++;


            if (!enteredPin.equals(secretPin)) {

                System.out.println("Wrong PIN! Attempts left: " + (maxAttempts - attempts) + "\n");

            }

        }


        // check why loop ended

        if (enteredPin.equals(secretPin)) {

            System.out.println("\nAccess Granted!");

            System.out.println("It took you " + attempts + " attempt(s).\n");


            // a simple menu controlled by while loop

            String choice = "";

            while (!choice.equals("exit")) {

                System.out.println("Choose an option:");

                System.out.println("1. Check Balance");

                System.out.println("2. Withdraw Money");

                System.out.println("3. Exit");

                System.out.print("Your choice: ");

                choice = sc.nextLine();


                if (choice.equals("1")) {

                    System.out.println("Your balance is $" + balance + ".\n");


                } else if (choice.equals("2")) {

                    System.out.print("Enter withdrawal amount: ");

                    int amount = sc.nextInt();

                    sc.nextLine(); // consume leftover newline


                    if (amount <= 0) {

                        System.out.println("Invalid amount.\n");

                    } else if (amount > balance) {

                        System.out.println("Not enough balance!\n");

                    } else {

                        balance -= amount;

                        System.out.println("Withdrawal successful. Remaining balance: $" + balance + ".\n");

                    }


                } else if (choice.equals("3") || choice.equalsIgnoreCase("exit")) {

                    System.out.println("Logging out... Goodbye!");

                    choice = "exit"; // force exit


                } else {

                    System.out.println("Invalid choice! Try again.\n");

                }

            }


        } else {

            System.out.println("\nToo many wrong attempts! Your account is locked.");

        }


        sc.close();

    }

}


OUTPUT:

Enter your secret PIN: 0000 Wrong PIN! Attempts left: 2 Enter your secret PIN: 1234 Access Granted! It took you 2 attempt(s). Choose an option: 1. Check Balance 2. Withdraw Money 3. Exit Your choice: 1 Your balance is $1000. Choose an option: 1. Check Balance 2. Withdraw Money 3. Exit Your choice: 2 Enter withdrawal amount: 300 Withdrawal successful. Remaining balance: $700. Choose an option: 1. Check Balance 2. Withdraw Money 3. Exit Your choice: 3 Logging out... Goodbye

MINI PROJECT: (While Loop - Simple Calculator)

Your project is to create a Java program that works like a very simple calculator.

The program should keep showing a menu until the user decides to exit.

Menu example:

1. Add two numbers

2. Subtract two numbers

3. Multiply two numbers

4. Divide two numbers

5. Exit

The program should ask the user for two numbers and perform the chosen operation. If the user enters an invalid choice, print Invalid option". The program should continue looping until the user chooses Exit.


While writing the program, make sure you use:
⦿ Scanner for input
⦿ A while loop to keep the program running until exit
⦿ If–Else statements to handle user choices
⦿ printf or println to display results


EXAMPLE OUTPUT:

=== Simple Calculator === Choose an option: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Exit Your choice: 1 Enter first number: 10 Enter second number: 5 Result: 10 + 5 = 15 Choose an option: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Exit Your choice: 4 Enter first number: 20 Enter second number: 4 Result: 20 / 4 = 5.0 Choose an option: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Exit Your choice: 4 Enter first number: 10 Enter second number: 0 Invalid: Division by zero Choose an option: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Exit Your choice: 6 Invalid option! Try again. Choose an option: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Exit Your choice: 5 Exiting calculator. Goodbye! 


CLOSING
That's it for while loop in java. While loop is like checking first if baby has candy before crying. Do-while is like the baby crying at least once before even checking.