Logical OR and logical OR confounded by java? [closed]

六月ゝ 毕业季﹏ 提交于 2020-01-06 15:39:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!