0
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");
     }
  }
}

我怎样才能改变这一点,以便最后只收到一条消息?现在它给出了所有的信息,或者只是它们不同。我知道我不能真正休息,因为这不是一个循环,但我可以在这个问题上采取什么行动?我必须重写它吗?感谢您的帮助。

4

3 回答 3

1

String output = "";,然后将所有System.out.printlns 替换为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);
于 2013-09-29T02:17:36.667 回答
0

我不确定组、列和部分之间的关​​系,但是您可以在首先检查最具体的情况时执行类似的操作。这避免了许多级别的嵌套条件。

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");
}

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

于 2013-09-29T02:50:29.190 回答
0
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 使用 else 条件。

于 2013-09-29T02:20:26.120 回答