Java-If-Else逻辑

Java-If-Else逻辑,java,if-statement,Java,If Statement,我很难理解为什么第二个字符串不打印。即使我注释掉“第三个字符串”打印行,也没有输出 public class SecretMessage { public static void main (String [] args) { int aValue=4; if (aValue > 0){ if (aValue == 0) System.out.print("firs

我很难理解为什么第二个字符串不打印。即使我注释掉“第三个字符串”打印行,也没有输出

public class SecretMessage {
       public static void main (String [] args) {
            int aValue=4;
            if (aValue > 0){
                if (aValue == 0)
                System.out.print("first string   ");
        }
        else 
        System.out.println("second string   ");
        System.out.println("third string   ");
        }
    }
为什么“第二个字符串”不打印?我认为else块下的任何内容都会被执行,所以第二个和第三个字符串都应该被打印出来


提前谢谢

因为aValue在代码中总是大于4,即
aValue=4

此外,您还需要注意括号

public class SecretMessage {
       public static void main (String [] args) {
            int aValue=4;
            if (aValue > 0){
                if (aValue == 0)
                    System.out.print("first string   ");
            }
            else 
                System.out.println("second string   ");
            System.out.println("third string   ");
        }
    }
与下面的代码相同(但读起来不那么清晰),这里更清楚地解释了为什么只打印第二个字符串


如果我们正确缩进代码并编写(隐式)大括号,那么发生的事情就显而易见了:

public class SecretMessage {
    public static void main (String[] args) {
        int aValue = 4;
        if (aValue > 0){
            if (aValue == 0) {
                System.out.print("first string");
            }
        } else /* if (avalue <= 0) */ {
            System.out.println("second string");
        }
        System.out.println("third string");
    }
}
公共类秘密消息{
公共静态void main(字符串[]args){
int aValue=4;
如果(aValue>0){
如果(aValue==0){
系统输出打印(“第一个字符串”);
}
}else/*if(avalue 0
),而不是内部的
if
a==0
)。因此,不会输入
else
。因此只执行
System.out.println(“第三个字符串”);

关于代码的一些备注:

  • 如果输入了内部
    if
    ,则永远无法输入内部
    。如果输入了外部
    if
    ,则
    i
    >0
    ,因此不能为
    ==0
  • 您使用的是
    System.out.print(…)
    System.out.println(…)
    。我觉得您想使用其中一种。为了便于阅读,您还可以忽略这些语句中的尾随空格
  • 数组括号(
    []
    )应该直接跟在类型后面,没有空格(
    String[]args
    ->
    String[]args
if
仅当
条件
时才会执行块
否则仅当
条件
时才会执行块


您需要将其移动到第一个
if
块这是一个很好的例子,说明了为什么代码的形成和正确的缩进很重要,以及为什么人们应该总是编写
{
}
围绕
if
-,
else
-,
for
-,…正文。使用适当的编辑器格式化代码,以便您可以看到正在发生的事情。适当的缩进使它看起来更清晰。我建议您改用什么(始终使用
{}
)。您将
aValue
设置为4,然后检查它是否大于0。4确实大于0。为什么希望执行
if
条件的
else
块?也就是说,为什么希望
4>0
为false?
public class SecretMessage {
    public static void main (String[] args) {
        int aValue = 4;
        if (aValue > 0){
            if (aValue == 0) {
                System.out.print("first string");
            }
        } else /* if (avalue <= 0) */ {
            System.out.println("second string");
        }
        System.out.println("third string");
    }
}
if(condition){
    //code
}else{
    //othercode
}