Java .txt用户名和密码无效

时间:2016-01-30 19:19:31

标签: java netbeans passwords username

我只是尝试使用java(NetBeans),我虽然是基于快速文本的冒险游戏。我试图让它在两个文本文件中检查您的用户名和密码" users.txt"和" passwords.txt"我正在关注编程洞穴

的指南

以下是导入

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());

//循环未运行(不是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循环不运行,这在未打印时确认"循环运行时,User / Pass",这不是if / then语句错误,因为我添加了如果用户名是对或错,则打印else语句。请帮忙,谢谢马修。

1 个答案:

答案 0 :(得分:0)

如果我理解正确的话:

两个文件:

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

我们希望:

  1. 继续阅读用户文件,直至文件结束或我们找到了我们的用户。
  2. 读取密码文件中的相应行并检查密码是否匹配。
  3. 检查代码,while((user = bufferedReader.readLine()) != null)很好地完成了第一部分。我们想继续阅读整个文件,试图找到我们的用户,对吗?

    但嵌套的时候看起来有点可疑。我们只需要检查给定用户的SINGLE密码,对吧? RIGHT?

    深入研究代码,我们看到:

    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 :这将退出给定的循环播放器,不会出现任何问题。

    让我们做一些休息/继续mashup!假设我们在生活中获胜"如果密码确实正确:

    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. 酷孩子现在使用Scanner。
    2. 自动关闭资源有益于我们的健康。
    3. 关于分离关注点和将域代码与UI混合的事情。在代码示例中。随你。
    4. 所以在这里,我们选择两个,现在作为一种方法:

      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;
      }