2016-12-04 87 views
-3

正如你所看到的,我有三個名字叫做s1,s2和s3。它應該按照字母順序放在新的行上,但「Ashley」不打印。 enter code here爲什麼我的詞典程序不能打印所有三個字符串?

public class Lex { 
static String s1 = "Ashley"; 
static String s2 = "Joe"; 
static String s3 = "John"; 
    public static void main(String[] args) { 
     String topString = ""; 
     String midString = ""; 
     String botString = ""; 

     if (s1.compareTo(s2) > 0 && (s1.compareTo(s3) > 0)) { 
      topString = s1; } 
      else if (s1.compareTo(s2) < 0 && (s1.compareTo(s3) > 0)) { 
      midString = s1; } 
       else{ botString = s1; } 

     if (s2.compareTo(s1) > 0 && (s2.compareTo(s3) > 0)) { 
      topString = s2; } 
      else if (s2.compareTo(s1) < 0 && (s2.compareTo(s3) > 0)) { 
      midString = s2; } 
       else { botString = s2; } 

     if (s3.compareTo(s2) > 0 && (s3.compareTo(s1) > 0)) { 
      topString = s3; } 
      else if (s3.compareTo(s2) < 0 && (s3.compareTo(s1) > 0)) { 
      midString = s3; } 
      else { botString = s3;} 

      System.out.println(topString); 
      System.out.println(midString); 
      System.out.println(botString); 
    } 
} 
+1

它看起來像你重新發明輪子。使用'Arrays.sort'或'Collections.sort' – 4castle

+0

@ 4castle我應該這樣做。我知道做數組更容易,但我必須這樣做,因爲「我們還沒有學過數組。」 –

+0

歡迎來到Stack Overflow!它看起來像你需要學習使用調試器。請幫助一些[互補調試技術](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。如果您之後仍然有問題,請隨時返回更多詳情。 –

回答

0

你的邏輯複雜,你正在嘗試的東西太多了在同一時間,這將使瞭解&閱讀邏輯就變得更難比較(也是你的代碼縮進不好)。

你可以嘗試下面的代碼與內嵌評論,將採取逐步比較和實現結果。

   if(s1.compareTo(s2) < 0) { //is s1 higher than s2 ? 
       if(s1.compareTo(s3) < 0) { //is s1 higher than s3 as well ? 
        topString = s1;//then topper is s1 
        if(s2.compareTo(s3) < 0) {//is s2 higher than s3 ? 
         midString = s2;//then mid is s2 
         botString = s3;//bot is s3 
        } 
       } else { 
        topString = s3;//s3 is topper compared to s1 and s2 
        midString = s1;//mid is s1 
        botString = s2;//bot is s2 
       } 
      } else {//means s2 is topper 
       if(s2.compareTo(s3) < 0) {//is s2 topper than s3 as well ? 
        topString = s2;//yes, so s2 is topper 
        if(s1.compareTo(s3) < 0) {//is s1 or s3 who is first ? 
         midString = s1;//s1 is first, so at middle 
         botString = s3;//s3 is bot 
        } 
       } else {//s2 is not topper than s3, but topper than s2 
        topString = s3;//top is s3 
        midString = s2;//mid is s2 
        botString = s1;//bot is s1 
       } 
      } 
相關問題