[英]In the code below the loop doesn't end even if I put the correct username
我試圖構建一個簡單的 UI,用戶在其中輸入用戶名,如果用戶名是 xyz,則將向用戶顯示“輸入您的密碼”。 如果密碼是 xyz1234,則將向用戶顯示“請等待加載...”,然后掃描儀退出。 如果用戶名不正確,我嘗試以某種方式對其進行編碼,以便在輸入正確的用戶名之前一直詢問用戶名。
顯然,代碼的第一部分有效,如果用戶名是 xyz,則代碼可以正常工作並顯示我想要的內容。 但是,如果用戶名在第一次嘗試時錯誤而在第二次嘗試時正確,它仍然繼續顯示“不正確的用戶名”而不是“輸入密碼”。
代碼如下所示:
import java.util.Scanner;
class User_Authentication
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter your Username");
String username=in.nextLine();
if(username.equals("xyz"))
{
System.out.println("Enter the Password");
String password=in.nextLine();
if(password.equals("xyz1234"))
{
System.exit(0);
System.out.println("Welcome");
System.out.println("Please wait while the system is loading....");
}
else
{
System.out.println("Your system has been locked for security reasons.");
System.out.println("Please contact an administrator to reset the password");
System.out.println("Any attempt to break in the computer will result in self destruction.");
System.exit(0);
}
}
else
{
do
{
if(username.equals("xyz"))
{
break;
}
System.out.println("Incorrect username");
System.out.println("Please try again");
in.nextLine();
}
while((username.equals("xyz"))==false);
}
}
} ```
你在 do-while 循環中說的in.nextLine()
,而不是username = in.nextLine()
替換它,它應該可以工作,但總的來說,你的 do-while 循環需要一些工作,它相對混亂。 這是我將如何處理它。
do {
System.out.println("Incorrect username");
System.out.println("Please try again");
username = in.nextLine();
} while(username.equals("xyz") == false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.