这段代码将一个字符串分离为令牌,并将它们存储在一个字符串数组中,然后将一个变量与第一个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");
    }
}

当前回答

有人在更高的帖子上说==用于int和检查null。 它也可以用来检查布尔运算和字符类型。

但是要非常小心,仔细检查你使用的是char类型而不是String类型。 例如

    String strType = "a";
    char charType = 'a';

对于字符串,您将检查 这是正确的

    if(strType.equals("a")
        do something

but

    if(charType.equals('a')
        do something else

是不正确的,你需要做下面的事情

    if(charType == 'a')
         do something else

其他回答

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");
}

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

满足Jorman

Jorman是一个成功的商人,他有两套房子。

但其他人并不知道。

还是那个乔曼吗?

当你问麦迪逊街或伯克街的邻居时,他们唯一能说的就是:

仅从住所来看,很难确定是同一个人。因为他们是两个不同的地址,所以很自然地假设他们是两个不同的人。

这就是运算符==的行为。它会说datos[0]==usuario是假的,因为它只比较地址。

一个救援的调查员

如果我们派个调查员去呢?我们知道是同一个乔曼,但我们需要证明。我们的警探会仔细检查身体的各个方面。通过彻底的调查,代理人将能够得出结论,是否是同一个人。让我们看看它在Java术语中的情况。

下面是String的equals()方法的源代码:

它逐个字符地比较字符串,以便得出它们确实相等的结论。

这就是String =方法的行为。因此datos[0].equals(通常)将返回true,因为它执行逻辑比较。

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

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

通常.equals用于对象比较,您想要验证两个对象是否具有相同的值。

==用于引用比较(两个对象是堆上相同的对象)&检查对象是否为空。它还用于比较基本类型的值。