-3

could any one help me to find problem on this code username and password verification.

username and password are predefined just checking this

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



    }

}
luiges90
  • 4,493
  • 2
  • 28
  • 43
Ferdous Wahid
  • 3,227
  • 5
  • 27
  • 28

1 Answers1

3

String comparison in java are done using equals method and not using == operator. Modify this condition :

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

to

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

equals compares the contents of the two strings whereas == checks whether two references point to the same memory object. Learn more about the difference on this related post: Java String.equals versus ==

Community
  • 1
  • 1
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • after correction it give me this messege... Exception in thread "main" java.lang.NullPointerException at org.test.Auth.authentication(UserAuth.java:43) at org.test.User.chackLogin(UserAuth.java:27) at org.test.UserAuth.main(UserAuth.java:78) – Ferdous Wahid Sep 29 '13 at 11:09
  • @user2828176 either your u.username or u.password is null. You need to put a null check before checking for equalitu. – Juned Ahsan Sep 29 '13 at 11:11