简体   繁体   English

从文件读取时如何仅修复检查用户名和密码的数组的最后一行

[英]How to fix only last line of array being checked for username and password when read from a file

I am reading usernames from a csv file in the format 我正在从CSV文件中读取用户名,格式为

admin1, apple,  admin
staff1, orange, staff

with staff1 being on a new line and no matter how many lines I have, only the last line will be checked when login is occurring. 在staff1处于新行中时,无论我有多少行,登录时都会检查最后一行。

        AtomicBoolean found = new AtomicBoolean(false);

   btnLogin.setOnAction(e -> {
        while (in.hasNextLine()) {


            String s = in.nextLine().replaceAll("\\s+", "");





                if (name.equals(sArray[0]) && password.equals(sArray[1])) {
                    lMessage.setText("correct");
                    openMainForm();


                } else if (name.equals("") || password.equals("")) {
                    lMessage.setText("Please enter a username and password");


                } else {
                    lMessage.setText("Please enter valid credentials");



                }




            }


        });

I expect that if the username and password combination is found in the file they will be able to login and not just if the username and password is the last in the time 我希望,如果在文件中找到了用户名和密码组合,他们将能够登录,而不仅仅是用户名和密码是最后一次登录

The problem is you are setting the action in a loop. 问题是您将动作设置为循环。 That is, one action object being created for every pair and then being assigned. 即,为每对创建一个动作对象,然后对其进行分配。 So, after last iteration, the action will be set to the latest object, which is obviously checking for last pair of username-password. 因此,在最后一次迭代之后,该操作将被设置为最新对象,这显然是在检查最后一对用户名密码。

the loop translates to something like, 循环转化为类似的东西,

setOnAction(actionobject1 that checks for admin1, apple, admin) setOnAction(检查admin1,apple,admin的actionobject1)

setOnAction(actionobject2 that checks for staff1, orange, staff) setOnAction(用于检查staff1,orange,staff的actionobject2)

That effectively keeps last created object and check only for last pair 这有效地保留了最后创建的对象并仅检查最后一对

You might want to modify your logic so that there is only one action object. 您可能需要修改逻辑,以便只有一个操作对象。 And then check for valid username-password pair. 然后检查有效的用户名密码对。

Something like this: 像这样:

btnLogin.setOnAction(e -> {

     while (in.hasNextLine() ) {
        // check condition here
        // don't forget to break when successful

      }
        in.close();
    });

Also, make sure you break the loop once successful pair is found. 另外,请确保一旦找到成功的配对,就中断循环。 Otherwise the same thing will happen. 否则会发生同样的事情。

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

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