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。
答案 0 :(得分:3)
如果你写的话会是6:
public static void sixOrSeven() {
byte q=5;
if (q==5) {
q+=1;
}
else {
q--;
q++;
}
System.out.println(q);
}
根据规范:
和statements,可以写成:
Statement:
StatementWithoutTrailingSubstatement
(...)
StatementWithoutTrailingSubstatement:
Block
(...)
(...)
所以我们最终得到:
if (Expression)
single statement (can be a block)
else
single statement (can be a block)
答案 1 :(得分:2)
检查评论
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或else]没有{},则为if-else逻辑。然后,下一个立即单一声明将被视为if if else else