问题
I use this methode in order to check if a link is valid but when I use a logical OR it doesn't work but it works when i use a logical AND it's weird. What do you think?
public String verification() {
String lien = URL.getText().toString();
if(titre.getText().toString().isEmpty())
{
return "titreEmpty";
}
else if (lien.isEmpty()) {
return "UrlEmpty";
} else if (!lien.contains("http")) {
return "notALink";
} else if (!lien.contains("skydrive") || !lien.contains("youtube") ) { //the logical OR doesn't work
return "linkInvalid";
}
return "bon";
回答1:
Take a look at your condition:
!lien.contains("skydrive") || !lien.contains("youtube")
What happens in case when lien
don't contain skydrive
?
Entire condition is evaluated to
true || whatever
which will be evaluated to true, regardless if lien
will contain youtube
or not (which represents whatever
).
Same goes for youtube
. If lien
will not contain youtube
, condition must be evaluated to true
because it will be whatever || true
.
If you want to write condition that will say
if it is not true that line contains `skydrive` or line contains `youtube`
^^^^^^^^^^^^^^ ( ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^ )
if( ! ( a | b ) )
you need to write it as
if ( ! ( line.contains("skydrive") || line.contains("youtube") ) )
or using De Morgan's laws !( a | b )
<==> !a && !b
like
if ( !line.contains("skydrive") && !line.contains("youtube") )
and here you have little proof of De Morgan's law where 1 = true
, 0 = false
a | b | !a | !b | a|b | !(a|b) | !a & !b
--+---+----+----+-----+--------+---------
0 | 0 | 1 | 1 | 0 | 1 | 1
0 | 1 | 1 | 0 | 1 | 0 | 0
1 | 0 | 0 | 1 | 1 | 0 | 0
1 | 1 | 0 | 0 | 1 | 0 | 0
which shows that result of each case of a
and b
is the same for !(a|b)
and !a & !b
回答2:
you are using an "!" so that means if something doesnt equal to something else
you are talking about this line right ?
else if (!lien.contains("skydrive") && !lien.contains("youtube") )
with simple words, AND activates when lien does NOT contain skydrive AND youtube, OR activates when lien does NOT contain skydrive OR youtube, which would mean it would activate all the time
you are only getting confused because of the "!" :P
来源:https://stackoverflow.com/questions/20443398/logical-or-and-logical-or-confounded-by-java