while循环打印行错误

v2g6jxz6  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(347)
import java.util.Scanner;

public class US_Defense {
    public static void main(String[] args) {
        System.out.println(" ------------------------------------- ");
        System.out.println("  Welcome to the U.S. Defense Network  ");
        System.out.println(" ------------------------------------- ");
        System.out.println("   Please Input your password below.   ");
        System.out.println(" ------------------------------------- ");  

        String pass = "";
        while(!pass.equals("0286139") ){
            System.out.println(" ------------------------------------- ");
            System.out.println("     Incorrect password. Try again.    ");
            System.out.println(" ------------------------------------- ");

            Scanner input = new Scanner(System.in);
            System.out.print("  >: ");
            pass = input.nextLine();
        }
    }
}

当我单击run时,它会显示欢迎并输入密码部分,但随后它会显示不正确的密码和用户输入提示。我试着让这样的代码只说欢迎和输入密码,但它没有这样做。

omhiaaxx

omhiaaxx1#

do-while 循环可能是最干净的解决方案。冲水是个好主意 System.out 当你 print (如果不包含新行,则不存在隐式刷新)。如果你真的想 while 循环您可以使用赋值解析到右侧的事实,如:

Scanner input = new Scanner(System.in);
System.out.print("  >: ");
System.out.flush();
String pass;
while (!(pass = input.nextLine()).equals("0286139")) {
    System.out.println(" ------------------------------------- ");
    System.out.println("     Incorrect password. Try again.    ");
    System.out.println(" ------------------------------------- ");

    System.out.print("  >: ");
    System.out.flush();
}

但是,一个 do-while (如前所述)会更干净,看起来像

Scanner input = new Scanner(System.in);
do {
    System.out.print("  >: ");
    System.out.flush();
    String pass = input.nextLine();
    if (pass.equals("0286139")) {
        break;
    }
    System.out.println(" ------------------------------------- ");
    System.out.println("     Incorrect password. Try again.    ");
    System.out.println(" ------------------------------------- ");
} while (true);

相关问题