1、do.....while循环:
测试代码1:
package test.com.dowhile;
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("The value of i is: " + i);
i++;
} while (i <= 5);
}
}
测试代码2:
package test.com.dowhile;
public class NestedDoWhileExample {
public static void main(String[] args) {
int outer = 1;
do {
System.out.println("Outer loop iteration: " + outer);
int inner = 1;
do {
System.out.println("Inner loop iteration: " + inner);
inner++;
} while (inner <= 3);
outer++;
} while (outer <= 5);
}
}
测试代码3:
package test.com.dowhile;
public class VeryComplexDoWhileExample {
public static void main(String[] args) {
int sum = 0;
int i = 0;
int j = 0;
int maxIterations = 5;
do {
System.out.println("Outer loop iteration: " + i);
i++;
j = 0;
// Inner loop to calculate the sum of squares
do {
sum += j * j;
System.out.println(" Inner loop iteration: " + j + ", sum: " + sum);
j++;
} while (j < i);
} while (i < maxIterations);
System.out.println("Final sum of squares: " + sum);
}
}
测试代码4:
package test.com.dowhile;
//一个带有嵌套循环、条件语句和do-while循环。
//该程序包含一个外部do-while循环和一个内部do-while循环,分别用于迭代外部循环和内部循环,每次迭代期间都会完全执行。
public class ComplexDoWhileExample {
public static void main(String[] args) {
int i = 0;
int j = 0;
do {
System.out.println("Outer loop iteration: " + i);
i++;
j = 0;
do {
System.out.println(" Inner loop iteration: " + j);
j++;
} while (j < 10);
} while (i < 3);
}
}
测试代码5:用do..while循环模拟用户登录
package test.com.dowhile;
import java.util.Scanner;
//用do..while循环模拟用户登录,只有在用户输入正确的用户名和密码后才能退出循环。
//使用一个布尔变量标记用户是否成功登录,并使用do..while循环来反复要求用户进行尝试,直到成功登录或者达到最大尝试次数。
//如果用户成功登录,布尔变量loggedIn将被设置为true,从而退出循环。
//如果达到最大尝试次数,程序会提醒用户并且退出循环。这种方式可以很好地处理多次交互,并且提供最大尝试次数的限制。
public class LoginExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String username = "admin";
String password = "1234";
boolean loggedIn = false;
int attempts = 0;
final int MAX_ATTEMPTS = 3;
do {
System.out.print("请输入用户名: ");
String inputUsername = scanner.nextLine();
System.out.print("请输入密码: ");
String inputPassword = scanner.nextLine();
if (inputUsername.equals(username) && inputPassword.equals(password)) {
System.out.println("登录成功!");
loggedIn = true;
} else {
System.out.println("用户名或密码错误,请重试");
attempts++;
}
if (attempts >= MAX_ATTEMPTS) {
System.out.println("达到最大尝试次数,退出程序");
break;
}
} while (!loggedIn);
}
}
运行结果如下:
2、for循环,while循环,do...while... 循环,三种循环的区别:
package test.com.dowhile;
//三种循环的区别
public class LoopExamples {
public static void main(String[] args) {
// for循环
for (int i = 0; i < 3; i++) {
System.out.println("for循环: i = " + i);
}
// while循环
int j = 0;
while (j < 8) {
System.out.println("while循环: j = " + j);
j++;
}
// do..while循环
int k = 0;
do {
System.out.println("do..while循环: k = " + k);
k++;
} while (k < 2);
}
}