+ -
当前位置:首页 → 问答吧 → 捷径运算子(&&)问题

捷径运算子(&&)问题

时间:2011-11-02

来源:互联网

Dear 各位前辈:

我是一个非本科系的java新手 , 想请教各位前辈, 捷径运算子 if(a&&b) 式中不是若a为false则就不执行b了吗??还是程式还是会执行??

我的想法是应该不会执行 , 但是下列的java program却显示是还是会执行 , 请各位前辈帮忙解惑 . 还是有啥观念小弟未考虑 ,还望赐教 , 谢谢 . ( /* */ 为我的想法 )

1
2
3
4
5
6
7
8
9
10
11
12
public class opTest{ public static void main(String[] args){ int x=5; boolean b1=true; boolean b2=false; if((x==4)&&!b2) /* 判断x==4,为false,执行下一句 (不是应该不会执行!b2)*/ System.out.print("1"); System.out.print("2"); /* 执行印出2 */ if((b2=true)&&b1) /* 判断b2=true,为false,执行下一句 */ System.out.print("3"); }
}


执行的结果为 : 23 (我的想法结果应该是: 2 )

作者: mmoooomm   发布时间: 2011-11-02

mmoooomm wrote:
Dear 各位前辈:

我是一个非本科系的java新手 , 想请教各位前辈, 捷径运算子 if(a&&b) 式中不是若a为false则就不执行b了吗??还是程式还是会执行??

我的想法是应该不会执行 , 但是下列的java program却显示是还是会执行 , 请各位前辈帮忙解惑 . 还是有啥观念小弟未考虑 ,还望赐教 , 谢谢 . ( /* */ 为我的想法 )

1
2
3
4
5
6
7
8
9
10
11
12
public class opTest{ public static void main(String[] args){ int x=5; boolean b1=true; boolean b2=false; if((x==4)&&!b2) /* 判断x==4,为false,执行下一句 (不是应该不会执行!b2)*/ System.out.print("1"); System.out.print("2"); /* 执行印出2 */ if((b2=true)&&b1) /* 判断b2=true,为false,执行下一句 */ System.out.print("3"); }
}


执行的结果为 : 23 (我的想法结果应该是: 2 ):)


1. 测试两个 boolean value 是否等值的 operator 是 ==(不是 =)

作者: Duncan   发布时间: 2011-11-02

Dear Duncan前辈 :
感谢你的回覆 , 我将程式改为

1
2
3
4
5
6
7
8
9
10
11
12
13
public class opTest{ public static void main(String[] args){ int x=5; boolean b1=true; boolean b2=false; if((x==4)&&!b2) System.out.print("1"); System.out.print("b2="+b2); System.out.print("2"); if((b2=true)&&b1) System.out.print("3"); }
}

执行结果为 : b2=false23 (所以我的想法 !b2 确实是未执行)
但是想请教一下 , 怎么会印出3呢 ?? (b2=true)这个判断怎会true 还望赐教谢谢

作者: mmoooomm   发布时间: 2011-11-02

mmoooomm wrote:
Dear Duncan前辈 :
感谢你的回覆 , 我将程式改为

1
2
3
4
5
6
7
8
9
10
11
12
13
public class opTest{ public static void main(String[] args){ int x=5; boolean b1=true; boolean b2=false; if((x==4)&&!b2) System.out.print("1"); System.out.print("b2="+b2); System.out.print("2"); if((b2=true)&&b1) System.out.print("3"); }
}

执行结果为 : b2=false23 (所以我的想法 !b2 确实是未执行)
但是想请教一下 , 怎么会印出3呢 ?? (b2=true)这个判断怎会true 还望赐教谢谢


1. !b 这个 expression 在 evaluate 之后不会改变 b 的值,所以依这程式码不能推论 !b2 确实未执行

作者: Duncan   发布时间: 2011-11-02

Dear Duncan前辈 :

万分感谢您的解惑 , 谢谢 .

作者: mmoooomm   发布时间: 2011-11-02