-3

I am matching two java Strings ,It matches most of the equal Strings but for some values it does not match even the Strings are totally same .

 public static Person SearchPersonByID(String id)
  {
    for(int i=0;i<personList.size();i++)
    {
    Person p=new Person();
    p=personList.get(i);
    String useride=p.UserId.toString();
    System.out.println(p.UserId+"=="+id);
    if(useride.contains(id)||useride.equals(id))
    {
        System.out.println("Matched");
        return p;   
    }

    }return null;

}

I have debugged the program ,although values are exactly same still it is returning null. Here is the values i want to match ..Kindly help me

ahsan7==ahsan7

they are same and yet it returns null


   public class Person {

String Status;
String MobileNo;
String Hobbies;
String PersonName;
String Password;
String LastSeen;
String UserId;
String location;
String Adress;
String EmailId;
String Type;
String ImageAdress;
int port;
DefaultListModel<String> FriendsList=new DefaultListModel<>();

Person()
{
}

 }
Charlie
  • 4,827
  • 2
  • 31
  • 55

2 Answers2

1

Try

userride.equalsIgnoreCase(id); for case insensitive comparisons
userride.equals(id) for case sensitive comparison

Probably what you can do is put a debug point at the if() and check the strings you are comparing..

rozar
  • 1,058
  • 3
  • 15
  • 28
1

length of p.userid is right but the length of argument String id always gives 990 . I changed the program... I splited a Message String using Message.Split(,); and then passed the String as Argument to the function

  public static Person SearchPersonByID(String id)
{
for(int i=0;i<personList.size();i++)
{
    Person p=new Person();
    p=personList.get(i);
     id=id.trim();
    String useride=id.toString();
    System.out.println(p.UserId.length()+"    compares   "+id.length());
    if(p.UserId.equals(useride))
    {
        System.out.println("Matched");
        return p;   
    }

}return null;

  }

and it works fine

Charlie
  • 4,827
  • 2
  • 31
  • 55
  • 1
    I think you should figure out why `id` is so large; to me that indicates a problem in your calling code. If you do want to keep the `trim()` in this function, I suggest moving it outside of the loop: only trim once, not every time through. Regardless, +1 for solving your own problem. – kdgregory Mar 27 '14 at 20:08