09 Java Fundamentals | While Loop in Java | By Dummy for Dummies
INTRODUCTION
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
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!");
}
}
POINTS TO REMEMBER
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");
}
}
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!");
}
}
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:
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: