2013-09-29 51 views
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"); 
    } 
    } 
} 

我怎么能改变这个,让我只在最后得到一个消息?现在它提供了所有的信息,或只是它们不同。我知道我不能把一个实际的休息,因为这不是一个循环,但我可以采取什么行动在这个问题?我需要重写吗?感谢您的帮助。如何在java上使用if语句结束一个结果?

+0

尽可能使用'else' .. – karthikr

回答

1

String output = "";,然后将所有的System.out.println s替换为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); 
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"); 
} 

使用其他条件与若。

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

它将工作只有当群体在所有列独一无二的 - 例如,检查两种生物是否相同物种,然后扩大,检查属,然后因为你赢了”家庭将是有效的在不同的属中有相同的物种名称;但是通过首先检查街道名称来测试房屋地址是否相同是无效的,因为您将在不同的城市中拥有相同名称的街道。

+1

这是不一样的逻辑。当名称相同但鳕鱼不同时,将您的代码与OP的代码进行比较。 – Bohemian

+0

如果组在所有列中都是唯一的,这是有效的;如果组在不同列中重复,则不是。我们并不真正了解数据以说明情况。我在紧跟在代码后面的段落中提到了这一点。 – alexroussos