While循环打印线错误

时间:2018-12-07 03:35:06

标签: java while-loop

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();
        }
    }
}

当我单击运行时,它会显示“欢迎使用”并输入密码部分,但随后会显示错误的密码和用户输入提示。我正在尝试使用,因此代码仅显示了欢迎和输入密码,但没有这样做。

1 个答案:

答案 0 :(得分:1)

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);