簡體   English   中英

Java用戶名和密碼輸入驗證

[英]java username and password input validation

我試圖提示用戶在出現提示時輸入他或她的用戶名和密碼。 在他們輸入之后,我試圖對照我與源代碼一起存儲的文本文件進行檢查。

public static void getCreds()
{
    String userName;
    String userPass;

    Scanner credsInput = new Scanner(System.in);

    System.out.print("Please enter your username: ");
        userName = credsInput.nextLine();
    System.out.print("Please enter your password: ");
        userPass = credsInput.nextLine();

    boolean found = false;
    String tempUser;
    String tempPass;
    //String fileName = "credentials.txt";

    try
    {
        // Scanner scan = new Scanner(new BufferedReader(new FileReader("credentials.txt")))
        Scanner scan = new Scanner(new File("credentials.txt"));
        scan.useDelimiter(",");

        while (scan.hasNext() && !found)
        {
            tempUser = scan.next();
            tempPass = scan.next();

            if(tempUser.trim().equals(userName.trim()) && tempPass.trim().equals(userPass.trim()))
            {
                found = true;
                System.out.println("success");
            }

        }

        scan.close();
    }

    catch (Exception e)
    {
        System.out.println("invalid");
    }


}

這是文本文件的內容。

user1,pass1
bob,1234
jim,1234

我不認為它實際上是從文件中讀取的,但是我可能是錯的,感謝您的幫助。

編輯

我忘了輸出。 當我編譯並運行代碼時,它會詢問用戶名並成功輸出,並且無論我是否輸入正確的代碼,它都會引發異常並顯示

invalid

編輯#2

我的第一個問題是我不習慣在Java中正確存儲文本文件。 之后,我將文本文件更改為正確的位置。 我能夠成功更改useDelimiter行

scan.useDelimiter(",|\n");

現在它可以成功檢查用戶名和密碼並輸出

Success

如果輸入在文本文件中。

我建議使用hasNextLine()和nextLine(),因為您知道用戶名和密碼對在單獨的行上。

    Scanner scan = new Scanner(new File("credentials.txt"));

    while (scan.hasNextLine() && !found)
    {
        String[] userNpwd = scan.nextLine().split(",");
        if(userNpwd.length() == 2)
        {
            tempUser = userNpwd[0];
            tempPass = userNpwd[1];
            if(tempUser.trim().equals(userName.trim()) && tempPass.trim().equals(userPass.trim()))
            {
                found = true;
                System.out.println("success");
             }
         }
    }

刪除用作分隔符的逗號,因為例如它將1234附加在回車符\\n作為令牌,我在IDE上嘗試如下:

   //scan.useDelimiter(",");

        while (scan.hasNext() && !found)
        {
            String line  = scan.nextLine();
            tempUser = line.split(",")[0];
            tempPass = line.split(",")[1];
            //..... complete the logic as it was

          }
         .....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM