2017-02-20 74 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\""); 

}