【问题标题】:Java .txt username and password not working [closed]Java .txt 用户名和密码不起作用[关闭]
【发布时间】:2016-01-30 19:19:30
【问题描述】:

我只是在尝试使用 java (NetBeans),并且想开发一个基于文本的快速冒险游戏。我试图让它在两个文本文件“users.txt”和“passwords.txt”中检查您的用户名和密码,我正在遵循Cave of Programming上的指南

这里是导入

import java.io.*;
import javax.swing.JFrame;

这是错误所在,

        private void loginActionPerformed(java.awt.event.ActionEvent evt) {                                      
       String usernametxt = "users.txt";
       String passwordtxt = "passwords.txt";  
       String user = null;
       String pass = null;
       try {
       // file reader for username \\
           FileReader fileReader = new FileReader(usernametxt);
           // file reader for password \\
           FileReader fr = new FileReader(passwordtxt);
           // buffered reader for username \\
           BufferedReader bufferedReader = new BufferedReader(fileReader);
           // buffered reader for password \\
               BufferedReader br = new BufferedReader(fr);
                // check for if user doesn't equal null \\
           while((user = bufferedReader.readLine()) != null){
               // if username equals first line of username.txt \\
               if (username.getText().equalsIgnoreCase(user)){
                   // check for if pass doesn't equal null \\
                   while((pass = br.readLine()) != null){
                   // if password equals first line of passwords.txt \\
                   if (password.getPassword().equals(pass)){
                       // if password = pass than it will exit \\
                   System.exit(1);
                }
                   // else continue \\
                   else{
                       continue;
                   }

               }
           }
       }
       bufferedReader.close();
       br.close();
   }
   catch(FileNotFoundException ex){
      System.out.println("Unable to open file ");
   }
   catch(IOException ex){
       System.out.println("Error reading file");
       }
    }    

这里是文本文件

users.txt
matthew

passwords.txt
matt

此处提供完整代码 http://textuploader.com/57urs

最新代码在这里 http://textuploader.com/577qk

随时在这里问我问题。

提前感谢您的帮助!

最新代码

private void loginActionPerformed(java.awt.event.ActionEvent evt) {                                      
   String usernames = username.getText();
   String passwords = password.toString();
   boolean signedin = false;
   String usernametxt = "users.txt";
   String passwordtxt = "passwords.txt";  
   String user = null;
   String pass = null;

   try {
       FileReader fr1 = new FileReader(usernametxt);
       FileReader fr2 = new FileReader(passwordtxt);

       BufferedReader br1 = new BufferedReader(fr1);
       BufferedReader br2 = new BufferedReader(fr2);

       System.out.println("Username: "+br1.readLine());
       System.out.println("Password: "+br2.readLine());

// While 循环未运行(不是 if 语句错误 \

       while ((user = br1.readLine()) != null){
           // checks if username is not equal to usernames.txt \\
           if (user.equalsIgnoreCase(usernames)){
               System.out.println("while loop running, username (right)");
               break;
               }
               else{
               System.out.println("while loop running, username (wrong)");
               }
           }
       br1.close();


           while ((pass = br2.readLine())!= null){
               if (pass.equalsIgnoreCase(passwords)){
                 signedin = true;
                 System.out.println("While loop running, password (right)");
                 break;
              }
              else{
                System.out.println("While loop running, password (wrong)
              }
       }
        br2.close();

// 注释掉 if 语句,因为我不想在测试时关闭 \

       //    if (signedin){
           //        System.out.println("SIGNEDIN = TRUE");
          //        new error1().setVisible(true);
        //       this.dispose();
   //   }
    //   if (!signedin){
     //      System.out.println("SIGNEDIN = FALSE");
     //      System.exit(1);
      // }

   }
   catch(FileNotFoundException ex){
       System.out.println("Unable to open file ");
   }
   catch(IOException ex){
       System.out.println("Error reading file");
   }
}                          

新问题

while 循环不运行,当它不打印“While loop running,User/Pass”时确认这一点,这不是 if/then 语句错误,因为我添加了 else 语句以打印 if 用户名是对还是错。请帮忙,谢谢马修。

【问题讨论】:

  • 你能提供一个堆栈跟踪吗?
  • 不是一个很好的代码实现。您正在使用嵌套的 while 循环。您可以先从单独列表中的两个文件中检索所有用户名和密码,然后开始进行比较。
  • 好吧,我试试看
  • 我如何获得堆栈跟踪?,我不知道那是什么
  • 当您的代码出现问题时,您必须告诉我们错误/异常是什么以及它们发生在哪里。同时发布 Stacktrace。如果您不知道从哪里获得,请在 Google 上搜索“[IDE 名称] stacktrace”之类的内容。

标签: java netbeans passwords


【解决方案1】:

如果我理解正确:

两个文件:

  • users.txt 包含用户名。
  • passwords.txt 保存密码。

我们想要:

  1. 继续读取用户文件,直到文件结束或我们找到我们的用户。
  2. 读取密码文件对应行,检查密码是否匹配。

检查代码,while((user = bufferedReader.readLine()) != null) 很好地完成了第一部分。我们确实想继续阅读整个文件以试图找到我们的用户,对吧?

但是嵌套的 while 似乎有点可疑。我们只需要检查给定用户的单一密码,对吗?对吗?

深入挖掘您的代码,我们看到:

if (password.getPassword().equals(pass)) {
    // if password = pass than it will exit
    System.exit(1);
} // plus Lots of code...

嘿!我不认为System.exit 做你想要的!

System.exit 将退出程序,返回 DOS 或这些天酷孩子正在使用的任何东西。它返回的整数称为错误代码,可用于将信息反馈给启动我们程序的终端/shell。

您最有可能寻找的关键字是 break:它将立即退出给定的循环,不问任何问题。

让我们做一些中断/继续混搭!如果密码确实正确,假设我们“赢得生活”:

boolean winAtLife = false;
while((user = bufferedReader.readLine()) != null){
    String candidatePassword = br.readLine();
    if (candidatePassword == null) {
        // So the password file is shorter than the userfile? 
        // We probably want to log or alert the poor DevOp guys. 
        // throwing an exception seems like the right thing to do here!
        break;
    }

    if (!user.equalsIgnoreCase(username.getText())) {
        // These are not the droid we're looking for, Better luck next line!
        continue;

        // Also notice that, since we KNOW that user can't be null,
        // we're using the force to save ourselves from dreaded NullPointerExceptions!
    }

    if (!candidatePassword.equals(password.getPassword())) {
        // Hmmm, wrong password, I guess?
        // Not sure what do do next, but we DO NOT need to keep looping
        // since we've found our droid/user/whatever.
        // So let's break and save some EC2 Cycles.
        break; 
    }

    // If we ever reach here, we got ourselves a winner!
    pass = candidatePassword
    winAtLife = true;
}

编辑:好的...所以我听说了:

  1. 现在很酷的孩子们都在使用扫描仪。
  2. 自动关闭资源对我们的健康有益。
  3. 关于关注点分离以及将域代码与 UI 混合的一些事情。在代码示例中。任何。

所以我们开始,取两个,现在作为一个方法:

public boolean checkCredentials(String username, String password) throws IOException {
    // these two are begging to be constants or inlined. 
    final String usernametxt = "users.txt";
    final String passwordtxt = "passwords.txt";

    if (username == null || password == null) {
        // You probably don't want this in production code.
        // Exceptions are your best friends when something unexpected occurs.
        return false;
    }

    try (final Reader fileReader = new FileReader(usernametxt);
         final Reader passwordReader = new FileReader(passwordtxt)) {

        Scanner userScanner = new Scanner(fileReader);
        Scanner passwordScanner = new Scanner(passwordReader);

        while(userScanner.hasNext()) {
            final String user = userScanner.next();
            if (!passwordScanner.hasNext()) {
                // So the password file is shorter than the userfile?
                // We probably want to log or alert the poor DevOp guys.
                // throwing an exception seems like the right thing to do here!
                return false;
            }
            final String candidatePassword = passwordScanner.next();
            if (!user.equalsIgnoreCase(username)) {
                // This is not the droid we're looking for
                // Also notice that, since we KNOW that user can't be null,
                // we're using the force to save ourselves
                // from dreaded NullPointerExceptions!
                continue;
            }

            if (!candidatePassword.equals(password)) {
                // Hmmm, wrong password, I guess?
                // Not sure what do do next, but we DO NOT need to keep looping
                // So let's return early and save some EC2 Cycles.
                return false;
            }

            // If we ever reach here, we got ourselves a winner!
            return true;
        }
    } // yay for autocloseable
    return false;
}

【讨论】:

  • 我现在试试这个,你也看到更新的代码了吗?
  • 不,忙着讲星球大战的笑话。 :)
  • 1. username.getText() 看起来像什么? 2. 我假设这两个文件都存在并且是可读的,好吗? :) 由于您正在执行两个不同的循环,因此无论密码是否在密码文件中,它都会匹配。这就是你想要的吗?
  • 两个文件都存在,users.txt 有一个用户“matthew”,passwords.txt 有一个密码“matt”。用户名是您输入文本的 jtextfield。现在我只做一个循环。现在我只是在试验 txt 文件。
  • 我已经编辑了答案以改善一些凉爽因素。现在是 21 世纪,办公室里的人们一直在谈论扫描仪之类的东西。无论如何,祝你的代码好运:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 2012-03-08
  • 1970-01-01
相关资源
最近更新 更多