2013-09-29 80 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