简体   繁体   English

While循环打印线错误

[英]While loop printing line incorrectly

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

When I click run it says the welcome and enter password part, but then it says incorrect password and the user input prompt. 当我单击运行时,它会显示“欢迎使用并输入密码”部分,但随后会显示错误的密码和用户输入提示。 I'm trying to have so the code only says welcome and input password but its not doing that. 我试图让代码只说欢迎和输入密码,但不这样做。

A do-while loop is probably the cleanest solution. do-while循环可能是最干净的解决方案。 It's a good idea to flush System.out when you print (if you don't include a new-line there isn't an implicit flush). print时刷新System.out是个好主意(如果不包括换行符,则不会隐式刷新)。 If you really want a while loop you can use the fact that assignment resolves to the right-hand side like: 如果您确实需要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();
}

But, a do-while (as mentioned) would be cleaner, and might look like 但是, 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM