![](/img/trans.png)
[英]equalsIgnoreCase returns false even when strings are same in java
[英]Why does equalsignorecase returns true even for non equal strings
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean x;
Scanner sc = new Scanner(System.in);
String igual = sc.next().toString();
String[] yes = new String[15];
yes[0]="When I find myself in times of trouble";
yes[1]="Mother Mary comes to me";
yes[2]="Speaking words of wisdom";
yes[3]="Let it be ";
yes[4]="And in my hour of darkness ";
yes[5]="She is standing right it front of me ";
yes[6]="mama just killed a man";
yes[7]="And when the broken hearted people ";
yes[8]="Living in the world agree ";
yes[9]="There will be an answer ";
yes[10]="For though they may be parted";
yes[11]="there is still a chance that they will see";
yes[12]="And when the night is cloudy";
yes[13]="There is still a light that shines on me";
yes[14]="Shine until tomorrow";
String[] no = new String[5];
no[0]="I wake up to the sound of music";
no[1]="Mother Mary comes to me";
no[2]="put a gun against his head";
no[3]="pulled my trigger now his dead";
no[4]="mama life had just began";
// searches in the yes array
for (int i=0 ; i<yes.length ; i++){
x=igual.trim().equalsIgnoreCase(yes[i].trim());
if (x=true){
System.out.println("true");
}
}
//searches in the no array
for (int j=0 ; j<no.length ; j++){
x = igual.trim().equalsIgnoreCase(no[j].trim());
if (x=true){
System.out.println("false");
}
}
}
}
即使您輸入的字符串僅等於數組中的字符串之一,也會打印15次true和5次false。 我調試了代碼,得到了結果,看來它在'if'條件內設置了'x'變量,謝謝。
作業返回其右側。 因此(根據您的if
陳述條件):
x=true
始終返回true
。 您可能正在尋找x == true
或更傳統的x
(就像if (x) {...}
)。 通常應首選較簡單的第二個變體。
使用等式表達式x == true
,而不是賦值表達式x = true
。
JLS, 第15.26章說了這一點
在運行時,賦值表達式的結果是賦值發生后變量的值。
因此,在代碼中
if (x = true)
x
分配為true
,然后if
評估為true
。 因此,無論您從equalsIgnoreCase
獲得的值如何,由於賦值表達式將返回true
,因此按equalsIgnoreCase
的語句將始終輸入if
塊。
另外,您不需要對布爾值進行條件檢查。 您可以簡單地使用
if (x) { // read as if x is true
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.