如何在 java 上以一个结果结束 if 语句


if (number1 + 8 == number2 || number1 - 8 == number2){
         if (name1.equals(name2)){
             if (cod1 == cod2){
                if (some1.equals(some2)){
                System.out.println("They're in the same group");
                }
             System.out.println("They are in the same column");;
             }
       System.out.println("They are in the same section");
       }
  System.out.println("They are in the same subgroup");
  }
    else{
    System.out.println("They are different");
     }
  }
}

我怎样才能改变它,以便最后只收到一条消息?现在它提供了所有消息或只是 他们是不同的。我知道我不能实际中断,因为这不是一个循环,但是我可以在这个问题上采取什么行动?我必须重写它吗?谢谢你的帮助。

String output = ""; ,然后将所有System.out.println替换为 output = 并将字符串更改为适当的输出。 此外,字符串赋值需要位于嵌套的 if 之前。

然后在最外层if else外,做System.out.println(output);

String output = "";
if (number1 + 8 == number2 || number1 - 8 == number2){
    output = "They are in the same subgroup";
    if (name1.equals(name2)){
        output="They are in the same section";
        if (cod1 == cod2){
            output="They are in the same column";
            if (some1.equals(some2)){
                output="They're in the same group";
            }
        }
    }
}
else{
    output="They are different";
}
System.out.println(output);
if (number1 + 8 == number2 || number1 - 8 == number2) {
    if ("abc".equals("def")) {
        if (cod1 == cod2) {
            if (some1.equals(some2)) {
                System.out.println("They're in the same group");
            } else
                System.out.println("They are in the same column");
            ;
        } else
            System.out.println("They are in the same section");
    } else
        System.out.println("They are in the same subgroup");
}
else {
    System.out.println("They are different");
}

将其他条件与 if 一起使用。

我不确定组、列和部分之间的关系,但您可以先检查最具体的情况,做这样的事情。这避免了嵌套条件的多个级别。

if (some1.equals(some2)) {
  System.out.println("They're in the same group");
} else if (cod1 == cod2) {
  System.out.println("They are in the same column");
} else if (name1.equals(name2)) {
  System.out.println("They are in the same section");
} else if (number1 + 8 == number2 || number1 - 8 == number2) {
  System.out.println("They are in the same subgroup");
} else {
  System.out.println("They are different");
}

只有当组在所有列中都是唯一的时,它才会起作用 - 例如,检查两个生物是否是相同的物种,然后扩大到检查属,然后家庭将是有效的,因为你在不同的属中不会有相同的物种名称;但是使用它来测试房屋地址是否相等,首先检查街道名称是无效的,因为您将在不同的城市拥有相同名称的街道。

最新更新