Topic: 使用&&与||的疑惑问题!!

  Print this page

1.使用&&与||的疑惑问题!! Copy to clipboard
Posted by: 1332185
Posted on: 2006-06-21 21:03

public class Test {
static boolean b=true;
private static int j=0;
public static boolean methodB(int k) {
j+=k;
return true;
}
public static void methodA(int i) {
b=i>10|methodB(1);
b=i>2&&methodB(4);//很迷惑的地方,&&为短路运算,不会执行“methodB(4)”,但程序运行结果确执行了。
} //使用“||”(同样为短路运算),但是它就不会执行“methodB(4)”.
public static void main(String args[]) {
methodA(5);
System.out.println(j+","+b);
}
}

``````````````````````````````````````````````````````
程序结果为:j=5、b=true

按理说结果为:j=1、b=true

请各位大哥们帮我讲讲为什么会这样呢?谢谢!

2.Re:使用&&与||的疑惑问题!! [Re: 1332185] Copy to clipboard
Posted by: jameszhang
Posted on: 2006-06-21 21:20

这是 “并“ 与 “或” 的 区别!

3.Re:使用&&与||的疑惑问题!! [Re: 1332185] Copy to clipboard
Posted by: why
Posted on: 2006-06-21 22:00

Dead
b=i>2&&methodB(4);
i == 4 => (i > 2) is true, so methodB(4) is executed.

try i = 2

4.Re:使用&&与||的疑惑问题!! [Re: 1332185] Copy to clipboard
Posted by: lisliefor
Posted on: 2006-06-22 10:09

二楼的说得有道理!
b = i>2 && methodB(4);
我的理解是:两个判断语句i>2 和 methodB(4)的并运算,只有两个式子全为true时,b的值为true;否则为false;
b = i>2 || methodB(4);
两个语句只要一个为true,b为true。

5.Re:使用&&与||的疑惑问题!! [Re: 1332185] Copy to clipboard
Posted by: dracularking
Posted on: 2006-06-22 11:39

public class Application
{
static boolean b = true;
private static int j = 0;
public static boolean methodB(int k)
{
j += k;
return true;
}

public static void methodA(int i)
{
b = i > 10 | methodB(1);
b = i > 2 && methodB(4); //很迷惑的地方,&&为短路运算,不会执行“methodB(4)”,但程序运行结果确执行了。
} //使用“||”(同样为短路运算),但是它就不会执行“methodB(4)”.

public static void main(String args[])
{
methodA(5);
System.out.println(j + "," + b);
}
}


you see, you said && is a shortcut operator, so that the function methodB(4)'s supposed not to be executed...

IN FACT, it's a wrong conclusion, it's executed indeed AS the former expression

"i>2" (here i is 5) is true, so the shortcut operator wont be shortcutted.

6.Re:使用&&与||的疑惑问题!! [Re: 1332185] Copy to clipboard
Posted by: 1332185
Posted on: 2006-06-24 00:11

谢谢你们的讲解!!


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923