为什么字符串不能相等比较?

5

可能是重复问题:
字符串不等于字符串?

我刚学Java,但是无法弄清楚这个代码块有什么问题。 我知道数组不是null,在其他地方测试过。也许是语法问题,我习惯于用c#编程。

     Scanner input = new Scanner(System.in);
     System.out.println("Enter ID :");
     String employeeId = input.nextLine();
     int index =  -1;
     for(int i = 0 ; i < employeeCounter ; i++)
     {
         if(employeeId == employeeNumber[i])
         {
           index = i;
         }
     }

     if(index == -1)
     {
         System.out.println("Invalid");
         return;
     }

我总是被带到“无效”的部分。有任何想法为什么会这样吗? 提前感谢。
employeeNumber [0]"12345" employeeId"12345" 但我不能进入第一个 if 语句,尽管 employeeId 等于 employeeNumber [0]

1
员工计数器是什么?请将完整代码粘贴。 - sgowd
3
在比较字符串时,请使用 .equals() 方法。 - tronbabylove
7个回答

12

不要使用 == 来比较字符串。

应该使用

if (string1.equals("other")) {
    // they match
}

2
“other”.equals(string1) 是首选方式——空值安全。 - Rudolf Mühlbauer

6

像这样比较字符串

if(employeeId.equals(employeeNumber[i]) {

}

4

正如其他人所指出的那样 - 提供完整的代码会更有帮助,但我猜测问题出在以下代码行:

if(employeeId == employeeNumber[i])

在比较两个字符串时,不要使用==。而应该使用equals()或equalsIgnoreCase()方法。==只检查对象的相等性,即employeeId和employeeNumber是否引用内存中的同一个对象。因此,对于对象,始终使用equals()方法。对于字符串,您还可以使用equalsIgnoreCase()方法进行不区分大小写的匹配。==应该用于原始类型,如int、long等。


3

当你使用==比较两个字符串时,实际上是在比较指针地址。为了比较两个字符串的内容,应该使用firststring.equals(secondstring)。


2

使用 equals() 方法来比较字符串

if(employeeId.equals(employeeNumber[i])){}

2

当您比较字符串时,请使用String1.equals(String2); 这应该会给您结果


0
"

\"==\"检查两个对象的引用是否相同。但equals()方法检查内容是相同还是不同。

"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接