2016-10-28 3 views
-1

세 단어를 알파벳순으로 처리하는 코드입니다. 아래쪽에있는 메서드를 제거하고 위의 코드에 메서드를 추가하려고합니다. 그러나, 나는 그렇게 할 수있는 작업 방법을 이해할 수 없다. 어떤 지침이나 도움을 주시면 고맙겠습니다. 감사합니다!두 가지 방법 합치기

System.out.print("Please enter three words: "); 
    final String words = keyboard.nextLine(); 
    final String[] parts = words.split(" "); 

    if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) { 
    System.out.println("All three of those words are the same!"); 

} else { 

     System.out.print("In alphabetical order those are: "); 
     alphabetizing (parts); 
     final int three = 3; 
     for (int limit = 0; limit < three; limit++) { 
     System.out.print(parts[limit] + " "); 
     } 
    } 
    } 

    public static void alphabetizing (final String[] parts) { 
     int word; 
     boolean check = true; 
     String temp; 

       for (word = 0; word < parts.length - 1; word++) { 
         if (parts[ word ].compareToIgnoreCase(parts[word + 1]) > 0) { 
            temp = parts[word]; 
            parts[word] = parts[word + 1]; 
            parts[word + 1] = temp; 
            check = true; 

         } 
       } 
     } 
    } 
+0

왜 이렇게할까요? –

+1

다른 방법으로 코드를 추출해야합니다. – Tom

+0

@ SkaryWombat 그것은 과제를위한 것입니다. 나는 그 방법을 제거하도록 요청 받았다. – Derrin

답변

0

어쨌든하고 싶어. 왜 작동하지 않을지 아무런 문제가 보이지 않습니다. 그냥 메서드를 호출하는 else 문에 추가하면 제대로 작동합니다.

System.out.print("Please enter three words: "); 
    Scanner keyboard = new Scanner(System.in); 
    final String words = keyboard.nextLine(); 
    final String[] parts = words.split(" "); 

    if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) { 
     System.out.println("All three of those words are the same!"); 

    } else { 

     System.out.print("In alphabetical order those are: "); 

     //boolean check = true; you don't neeed this. 
     String temp = ""; 

     for (int word = 0; word < parts.length - 1; word++) { 
      if (parts[word].compareToIgnoreCase(parts[word + 1]) > 0) { 
       temp = parts[word]; 
       parts[word] = parts[word + 1]; 
       parts[word + 1] = temp; 

      } 
     } 
     final int three = 3; 
     for (int limit = 0; limit < three; limit++) { 
      System.out.print(parts[limit] + " "); 
     } 

    } 

출력 :

Please enter three words: a b c 
In alphabetical order those are: a b c 
Please enter three words: a a a 
All three of those words are the same!