这段代码将一个字符串分离为令牌,并将它们存储在一个字符串数组中,然后将一个变量与第一个home…为什么它不工作?

public static void main(String...aArguments) throws IOException {

    String usuario = "Jorman";
    String password = "14988611";

    String strDatos = "Jorman 14988611";
    StringTokenizer tokens = new StringTokenizer(strDatos, " ");
    int nDatos = tokens.countTokens();
    String[] datos = new String[nDatos];
    int i = 0;

    while (tokens.hasMoreTokens()) {
        String str = tokens.nextToken();
        datos[i] = str;
        i++;
    }

    //System.out.println (usuario);

    if ((datos[0] == usuario)) {
        System.out.println("WORKING");
    }
}

当前回答

==运算符比较Java中对象的引用。你可以使用字符串的equals方法。

String s = "Test";
if(s.equals("Test"))
{
    System.out.println("Equal");
}

其他回答

equals()函数是Object类的一个方法,程序员需要重写它。String类重写它,以检查两个字符串是否相等,即在内容和不引用。

==运算符检查两个对象的引用是否相同。

考虑程序

String abc = "Awesome" ;
String xyz =  abc;

if(abc == xyz)
     System.out.println("Refers to same string");

这里的abc和xyz,都是指同一个字符串“Awesome”。因此表达式(abc == xyz)为真。

String abc = "Hello World";
String xyz = "Hello World";

if(abc == xyz)
    System.out.println("Refers to same string");
else
    System.out.println("Refers to different strings");

if(abc.equals(xyz))
     System.out.prinln("Contents of both strings are same");
else
     System.out.prinln("Contents of strings are different");

这里abc和xyz是两个具有相同内容“Hello World”的不同字符串。因此,表达式(abc == xyz)为假,而as (abc.equals(xyz))为真。

希望你理解==和<Object>.equals()之间的区别

谢谢。

It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.

唯一正确的方法是使用.equals() -> datos[0].equals(通常)。==表示仅当两个对象是object的相同实例(即。内存地址相同)

更新:01.04.2013我更新了这篇文章,因为下面的评论是正确的。最初我声明实习(String.intern)是JVM优化的副作用。虽然它确实节省了内存资源(这就是我所说的“优化”),但它是语言的主要特征

使用Split而不是tokenizer,它肯定会为你提供准确的输出 如:

string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}

在此之后,我相信你会得到更好的结果.....

a==b

比较引用,而不是值。在对象引用中使用==通常仅限于以下情况:

比较一个引用是否为空。 比较两个enum值。这是因为每个枚举常量只有一个对象。 您想知道两个引用是否指向同一个对象

“a”“b”equals()。

比较值是否相等。因为这个方法是在Object类中定义的,所有其他类都是从Object类派生出来的,所以它是为每个类自动定义的。但是,它不会对大多数类执行智能比较,除非类重写它。对于大多数Java核心类,它都以一种有意义的方式定义。如果它不是为(用户)类定义的,它的行为与==相同。

.equals()将检查两个字符串是否具有相同的值,并返回布尔值,其中==操作符检查两个字符串是否为同一对象。