Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Weird problem.

Status
Not open for further replies.

Mike2020

Programmer
Mar 18, 2002
55
US

Hi,

I get into a weird problem that I really don't know what happen. I get the string from the vector, the string have something like this:
CreateAccount 1 2000
CreateAccount 2 3000
CreateAccount 3 3300

As you can see, I do a split on the string to get the CreateAccount out of the string, and run this comparation with "CreateAccount", and it return all false.
I tried to see whether it have space around the word, and it doesn't has any. So anyone know what happen?


for (int i = 0; i < vsize; i++)
{
String Cmd = (String)vAccounts.elementAt(i);
String splitString[] = Cmd.split(" ");
String C = parseString(splitString[1]);
//System.out.println("String: #" + C + "#");
if (C == "CreateAccount")
{System.out.println("Line " + i + ": " + Cmd); }

}

Thanks....
Mike
 
Code:
    if (C.equals("CreateAccount"))
    {System.out.println("Line " + i + ": " + Cmd); }
// use equals for comparing String
 
Code:
import java.util.*;
class eq
{
public static void main(String args[])
       {
        Vector vAccounts = new Vector();
        vAccounts.add("CreateAccount 1 2000");
        vAccounts.add("CreateAccount 2 3000");
        vAccounts.add("CreateAccount 3 3300");
        int vsize = vAccounts.size();
        for (int i = 0; i < vsize; i++) 
            { 
             String Cmd = (String)vAccounts.elementAt(i);    
             String splitString[] = Cmd.split(" ");
             System.out.println("*"+splitString[0]+"*");
             System.out.println(Integer.parseInt(splitString[1]));
             //System.out.println("String: #" + C + "#"); 
             if (splitString[0].equals("CreateAccount")) 
                {System.out.println("Line " + i + ": " + Cmd); }
 
            }
       }
}
 
Just a little background on this. First time I faced this, I couldn't figure out what was happening.

In Java, Strings are objects, so if you use the == operator, you're asking the JVM if the objetcs are the same, ie, if they reference the same memory area.

By using the equals method, you test wether the content of the String object, ie the string itself, match.

Cheers.

Dian.
 

Hey Folks,

Thank you so much.....
I really don't know why it uses this way to do comparation, and it work.

Thanks again.

Mike
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top