2如果语句背对背

问题描述 投票:0回答:2
int x = 9; int y = 8; int z = 7;

    if(x>9)
    if(y>8)
       System.out.println("x>9 and y>8");
    else if(z>=7)
       System.out.println("x<=9 and z>=7");
    else
      System.out.println("x<=9 and z<7");

首先,我首先查看if语句,这是不可能的。这就是为什么我继续并寻找另一个(如果不可能),现在转到另一个(如果可能)的原因。这就是为什么我认为输出为("x<=9 and z>=7")

但是,什么也没出现。我想念什么?

java if-statement indentation
2个回答
1
投票

您没有括号,您发布的代码等效于

if (x > 9) {
    if (y > 8) {
       System.out.println("x>9 and y>8");
    } else if (z >= 7) {
       System.out.println("x<=9 and z>=7");
    } else {
       System.out.println("x<=9 and z<7");
    }
}

我只能根据您的问题和想要的消息来假设

if (x > 9 && y > 8) {
    System.out.println("x>9 and y>8");
} else if (z >= 7) {
   System.out.println("x<=9 and z>=7");
} else {
   System.out.println("x<=9 and z<7");
}

if (x > 9) {
    if (y > 8) {
        System.out.println("x>9 and y>8");
    }
} else if (z >= 7) {
   System.out.println("x<=9 and z>=7");
} else {
   System.out.println("x<=9 and z<7");
}    

简而言之,不要省略括号。


0
投票

尝试一下:

    int x = 9;
    int y = 8;
    int z = 7;

    if (x > 9) {
        if (y > 8) {
            System.out.println("x>9 and y>8");
        }
    } else if (z >= 7) {
        System.out.println("x<=9 and z>=7");
    } else {
        System.out.println("x<=9 and z<7");
    }

您需要在代码中加上括号以清除。

© www.soinside.com 2019 - 2024. All rights reserved.