Do While Loop
The do-while loop is a type of loop in programming that executes its block of code at least once before checking the condition. The loop will continue executing as long as the condition remains true.
Syntax:
Flow
Diagram:
Source Code:
import java.util.Scanner;
public class PositiveNumberCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("You entered: " + number);
scanner.close();
}
}Result:
Source Code:
import java.util.Scanner;
public class LoginCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String correctUsername = "admin";
String correctPassword = "1234";
String username, password;
do {
System.out.print("Enter username: ");
username = scanner.nextLine();
System.out.print("Enter password: ");
password = scanner.nextLine();
// !T=admin F || F !T=1234
if (!username.equals(correctUsername) || !password.equals(correctPassword)) {
System.out.println("Invalid username or password. Try again.");
}
} while (!username.equals(correctUsername) || !password.equals(correctPassword));
System.out.println("Login successful!");
scanner.close();
}
}Result:
Watch the video:

