【问题标题】:BufferedReader won't read [closed]BufferedReader 不会读取 [关闭]
【发布时间】:2016-09-07 21:35:39
【问题描述】:

我有一个程序,用户名和密码在一个文本文件中,文本文件如下所示:

election:12345

我有这段代码可以读取文件

try {
    BufferedReader read=new BufferedReader(new FileReader("election_un_pass.txt"));
    String line="";

    while((line=read.readLine())!=null) {
        String [] info=line.split(":");

        if(info[0].matches(Login.uname) && info[1].matches(Login.pass)){
            new Main();
        } else {
            JOptionPane.showMessageDialog(null, "Username or Password might not be correct");
        }
        Login.txtUName.setText("");
        Login.txtPassword.setText("");
     }
} catch (Exception e1) {
    e1.printStackTrace();
}

每次我运行我的程序时,即使我输入的用户名和密码是正确的,Username or Password might not be correct 消息仍然会出现,new Main() 不会出现。

【问题讨论】:

  • 请检查 Login.uname 和 Login.pass 值似乎它们不匹配。
  • 确定不想使用String.equalsLogin 的值是多少?
  • @VuralAcar 哦,它们实际上是匹配的,并且 Login.uname 和 Login.pass 被初始化为 txtUName.getText() 和 txtPassword.getText() 但由于你的建议,我只是直接使用了 txtUName .getText() 和 txtPassword.getText()。非常感谢!!!!
  • @Marvin txtUName.getText()txtPassword.getText() 但我现在只是直接使用它们,现在已经修复了,非常感谢!!!

标签: java file oop bufferedreader


【解决方案1】:

你可以:

  1. 了解如何在您使用的任何 IDE 中进行调试。使用调试模式,您可以一次执行一行代码并查看每个点的变量值。
  2. 发生错误时增加日志信息

例如,您可以打印到控制台/日志/对话框:

String msg = String.format("could not find user name: [%s] and password: [%s] in line: [%s]", Login.uname, Login.pass, line);

显然,出于安全原因,当输入错误值时,您不应在任何地方打印预期的用户名和密码,但这可能是找出问题所在的快速方法 :) 它可以像尾随空格字符一样简单某处或某处不正确的情况。

【讨论】:

    【解决方案2】:

    您确定要使用String.matches(regex) 进行比较吗?该参数被视为正则表达式,因此Login.unameLogin.pass 值中的任何正则表达式元字符都将被解释为正则表达式。这意味着您的匹配可能会以您意想不到的方式发挥作用。

    我怀疑你真的想说:

    if (info[0].equals(Login.uname) && info[1].equals(Login.pass)) {
    

    改为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-04
      • 2017-06-09
      • 2015-08-31
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      相关资源
      最近更新 更多