2017-02-20 42 views
-1

所以,我想爲什麼endsWith()不能使用||運營商?

String x = "[email protected]" // <--- it's .com 

if (!x.trim().toUpperCase().endsWith(".COM")) 
{ 
    System.out.println("Your E-mail is missing a \".com\""); 
} 

else 
{ 
    System.out.println("Welcome, " + x); 
} 

和它的工作完美的罰款

但是當我嘗試包括與另一說法||運營商,那麼它根本不會

String x = "[email protected]"; // <--- now it's .edu 

if (!x.trim().toUpperCase().endsWith(".COM") || !x.trim().toUpperCase().endsWith(".EDU")) 
{ 
    System.out.println("Your E-mail is missing a \".com\""); 
} 

else 
{ 
    System.out.println("Welcome, " + x); 
} 

自從我包括

|| !x.trim().toUpperCase().endsWith(".EDU"); 

if語句,我不斷收到我打印出來

+2

因爲這兩個條件是互相排斥的。該檢查總是如此,因爲您的電子郵件永遠不會以''.COM''和''.EDU'結尾。 – f1sh

+1

這裏有個合乎邏輯的問題。 – AxelH

+2

'||'是或,你想要什麼,哪個是'&&' – niceman

回答

0

看起來你應該有&&而不是||。如果我正確閱讀你的意圖,你想確保電子郵件地址以.com或.edu結尾。相反,你的條件檢查,如果你不結束。假設你以.com結尾,第一部分或將是假的,第二部分將被評估。 "foo.com".toUpperCase().endsWith(".edu")是錯誤的,所以!"foo.com".toUpperCase().endsWith(".edu")爲真,因此false || !"foo.com".toUpperCase().endsWith(".edu")爲真,因此整個條件計算結果爲true,並輸入if代碼塊。

+0

哦,我不知道我必須使用&&而不是||,Java很奇怪。謝謝 –

+1

@DannyDomazed - 這與Java怪異無關。這只是很好的舊布爾邏輯咬你。 –

+0

@IanMcLaird :-( –

0

如果您嘗試錯誤工作查看電子郵件是.com還是.edu使用爲

String x = "[email protected]"; 
if (!(x.trim().toUpperCase().endsWith(".COM") || x.trim().toUpperCase().endsWith(".EDU"))){ 
System.out.println("Your E-mail is missing a \".com\""); 

}