有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

netbeans如何使用文件流在Java中创建登录表单?

你好,我是一名java新手,我一直在研究一个包含(用户-图书馆工作人员和书籍)的图书馆系统,所以我试图创建一个登录表单。我已经有一个数组列表,但我做了一个文件流(为了澄清,我让新用户注册,他/她的信息将像此ID名称密码年龄一样保存到文件中),因此我尝试在library users类中使用此方法

      private Scanner x;
      private String user_name , password ;
      public void openfile(){
      try {x= new Scanner (new File ("E:\\javaapplication1
      \\test\\professors.txt"));
              }
      catch(Exception e){
      System.out.println("couldn't find file");
      }
      }
      public void checklog ( String username , String password ){
       String a , b ,c ,d ;


       while(x.hasNext()){
       a = x.next();
       b = x.next();
       c = x.next();
       d = x.next();

       if ( b == username ||c == password ){

        System.out.println("Loggin successful ");

       }
       else
           System.out.println("Loggin failed wrong id or password ");
        break;

然后用完整的代码在main中这样调用它

        System.out.println ("Enter your name ");
        check_name = reader.next();
        System.out.println ("Enter your password ");
        check_password =reader.next();
         lib_us professor ;
             professor = new lib_us(); 

             professor.openfile();
             professor.checklog(check_name, check_password);

我把所有的密码都搞错了,我把它们像4个id、名字、密码和年龄一样保存起来,这就是为什么我创建了一个b c和d

我仍然是这种登录表单的新手,因此请为我指定一个解决方案,如果您需要完整的代码,请索取:)


共 (1) 个答案

  1. # 1 楼答案

    因此,在checkLog()方法中,语句if(b == username || c == password)应该是if(b.equals(username) && c.equals(password))if(b.equalsIgnoreCase(username) && c.equalsIgnoreCase(password))表示区分大小写,或者不区分大小写(使用equals()方法区分大小写,或者使用equalsIgnoreCase()方法区分大小写)

    明白为什么吗?因为在你最初的声明中,你说只有其中一个是真的才能成功登录。在修订后的版本中,两者都必须是真实的。此外,不应使用运算符==来比较两个字符串,以确定它们是否是相同的字符串。这只会比较他们的地址

    编辑: 如果您的文件类似于以下所示:

    12姓名通行证12

    13 Namez Passz 13

    14姓名通行证14

    请尝试阅读以下代码并进行比较:

    private Scanner x;
    private String user_name, password;
    public void openFile()
    {
        try
        {
            x = new Scanner(new File("FILE PATH"));
        }
        catch(Exception e)
        {System.out.println("Couldn't find file"); System.exit(0);}
    }
    
    public boolean checklog(String username, String password)
    {
        String temp;
        String[] info;
    
        while(x.hasNext())
        {
            temp = x.nextLine();
            info = temp.split(" ");
    
            //info[0] = id, info[1] = username, info[2] = password, info[3] = age;
            //Right here that means the username and password is correct
            if(info[1].equals(username) && info[2].equals(password))
            {
                System.out.println("Login Successful");
                return true;
            }
        }
        System.out.println("Login failed wrong id or password");
        return false;
    }