gpt4 book ai didi

java - 不带大括号的 if-else 行为 : How is the answer 7 and not 6?

转载 作者:行者123 更新时间:2023-12-01 16:50:28 25 4
gpt4 key购买 nike

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=55+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);
}

根据规范:

enter image description here

statements ,可写为:

Statement:
StatementWithoutTrailingSubstatement
(...)
StatementWithoutTrailingSubstatement:
Block
(...)
(...)

所以我们最终得到:

if (Expression) 
single statement (can be a block)
else
single statement (can be a block)

关于java - 不带大括号的 if-else 行为 : How is the answer 7 and not 6?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41114448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com