[英]if-else behaviour without braces: How is the answer 7 and not 6?
public class inc {
public static void main (String []args) {
inc.sixOrSeven();
}
public static void sixOrSeven() {
byte q=5;
if (q==5)
q+=1;
else
q--;
q++;
System.out.println(q);
}
}
我是计算机科学的新手,我的老师教了我一些有关增量和减量的概念。 当我运行程序时,控制台显示的答案是7。但是我开始怀疑答案本身。 由于q=5
5+1=6
,如果q不是5,那么5+1-1=5
? 答案怎么可能是7。
如果您这样写,那将是6:
public static void sixOrSeven() {
byte q=5;
if (q==5) {
q+=1;
}
else {
q--;
q++;
}
System.out.println(q);
}
根据规格:
和statement ,可以写成:
Statement:
StatementWithoutTrailingSubstatement
(...)
StatementWithoutTrailingSubstatement:
Block
(...)
(...)
因此,我们最终得到:
if (Expression)
single statement (can be a block)
else
single statement (can be a block)
检查评论
public static void sixOrSeven() {
byte q=5; // q is 5
if (q==5) // q == 5 true
q+=1; // q = q + 1 which is q = 5 + 1 = 6. That means Now q = 6
else // As if was true so this else is ignored
q--;
q++; // q++ means q = q + 1 = 6 + 1 = 7; So Now q = 7
System.out.println(q); // print q which is 7
}
如果[if or else]没有任何{}的if-else逻辑。 然后,下一个即时单个语句将被视为是否存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.