java用户名和密码输入验证

java用户名和密码输入验证,java,Java,我试图在提示时提示用户输入其用户名和密码。在他们输入后,我试图对照我与源代码一起存储的文本文件进行检查 public static void getCreds() { String userName; String userPass; Scanner credsInput = new Scanner(System.in); System.out.print("Please enter your username: "); userName =

我试图在提示时提示用户输入其用户名和密码。在他们输入后,我试图对照我与源代码一起存储的文本文件进行检查

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(),因为您知道用户名和密码对在单独的行上

user1,pass1
bob,1234
jim,1234
    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");
             }
         }
    }

删除用作delimeter的coma,因为它将以附加到回车符
\n
1234
作为标记,我在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

          }
         .....

你能解释一下为什么你认为它不是从文件中读取的吗?当你执行程序时发生了什么。它是否如您所期望的那样工作?是否使用了调试器?您将看到您正在使用的文件等。您至少需要提供输出,并分享您调试代码的详细信息。使用该.txt文件制作一个映射,用户名为Key,密码为Value,在用户输入username后,循环映射的键集,查看该用户名是否存在,如果不存在,请让他知道,如果存在,获取该密钥后面的值,并将其与密码进行比较,如果相同,则登录有效,否则,让他知道密码错误。