image.png

    1. package com.itheima.loop;
    2. import java.util.Scanner;
    3. public class DeadForDemo7 {
    4. public static void main(String[] args) {
    5. // 目标:学会三种死循环的定义:for while do...while
    6. // for (;;){
    7. // System.out.println("HelloWorld");
    8. // }
    9. // while (true){
    10. // System.out.println("HelloWorld"); // 经典写法
    11. // }
    12. // do { // 一个程序中只能写一个死循环,要不然写多个会报错
    13. // System.out.println("HelloWorld");
    14. // }while (true);
    15. // 在循环后面写代码必须要注释,要不然后面的代码都报错
    16. System.out.println("-----------------------");
    17. // 1.定义正确密码
    18. int okPassword = 520;
    19. // 使用键盘录入的API:Scanner 创建对象要写在循环外面,如果写在循环里面的话每次都会创建Scanner对象,浪费内存
    20. Scanner sc = new Scanner(System.in);
    21. while (true){ // 定义一个死循环让他一直判断密码是否正确,如果密码正确则break跳出循环
    22. System.out.println("请输入你的密码:");
    23. int passWord = sc.nextInt();
    24. if (passWord == okPassword){
    25. break;
    26. } else {
    27. System.out.println("密码输入错误");
    28. }
    29. }
    30. System.out.println("恭喜你输入正确");
    31. }
    32. }