java用户名和密码验证

时间:2013-09-29 10:49:14

标签: java

任何人都可以帮我找到这个代码用户名和密码验证的问题。

只需检查此

即可预定义用户名和密码
package org.test;
import java.util.*;

class User{


    public String username;
    public String password;

    public String getUsername() {
        return username;

    }
    public void setUsername(String username) {
        this.username = username;

    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;

    }
    public void chackLogin(){
         Auth a = new Auth();
         a.authentication();
    }


}


class Auth{

    User u;
// username and pass

    String auser="admin";
    String apass="admin"; 

    public void authentication(){

        if((u.username==auser) && (u.password==apass))
        {
            System.out.println("Login Succseeful sor the user "+" "+auser);
        }
        else{
            System.out.println("incorrect username or password");
        }


       }


}



public class UserAuth {

    public static void main(String[] args) {

        //scan Username
        Scanner user=new Scanner(System.in);
        String usern= user.next();

        //scan password
        Scanner pass=new Scanner(System.in);
        String passw= pass.next();

        //object of class USEr
        User u =new User();

        //set user and pass

        u.setUsername(usern);
        u.setPassword(passw);
        u.chackLogin();



    }

}

1 个答案:

答案 0 :(得分:3)

java中的字符串比较是使用equals方法完成的,而不是使用==运算符。修改此条件:

if((u.username==auser) && (u.password==apass))

if((u.username).equals(auser) && (u.password).equals(apass)))

equals比较两个字符串的内容,而==检查两个引用是否指向同一个内存对象。详细了解相关帖子的差异:Java String.equals versus ==