JAVA 프로그래밍

문제

사용자가 입력한 단어를 알파벳순으로 정렬하는 문제222입니다 이를 해결하는 프로그램의 다음 실행상태에 대해 빈칸을 채우세요 

프로그램의 실행순서 및 실행상태

1  public static void main( String[] args ) {  

2   String[] words = { "", "", "" };      
   main()
             [0]         [1]         [2]    
 words            

단어를 입력하세요: carrot
단어를 입력하세요: banana
단어를 입력하세요: apple

3   for ( int last = words.length - 1; 0 < last; last-- ) {  

4    for ( int index = 0; index < last; index++ ) {
   main()
             [0]         [1]         [2]    
 words  carrot   banana   apple 
  last  2 
 index  0 

5     if ( words[index].compareTo( words[index+1] ) > 0 ) {

6      words[index+1] = temp;      
   main()
             [0]         [1]         [2]    
 words  apple 
  last
 index
  temp

4    for ( int index = 0; index < last; index++ ) {

5     if ( words[index].compareTo( words[index+1] ) > 0 ) {

6      words[index+1] = temp;      
   main()
             [0]         [1]         [2]    
 words  banana 
  last
 index
  temp

4    for ( int index = 0; index < last; index++ ) {

3   for ( int last = words.length - 1; 0 < last; last-- ) {  

4    for ( int index = 0; index < last; index++ ) {

5     if ( words[index].compareTo( words[index+1] ) > 0 ) {

6      words[index+1] = temp;      
   main()
             [0]         [1]         [2]    
 words  carrot 
  last
 index
  temp

4    for ( int index = 0; index < last; index++ ) {

3   for ( int last = words.length - 1; 0 < last; last-- ) {  

apple banana carrot 

7  }


프로그램 코드

	import java.util.Scanner;
		
	public class WordSort
	{
1		public static void main( String[] args ) { 	
			Scanner scan = new Scanner( System.in );
2			String[] words = { "", "", "" };  				
			for ( int index = 0; index < words.length; index++ ) { 
				System.out.print( "단어를 입력하세요: " );
				words[index] = scan.next();
			}
	
3			for ( int last = words.length - 1; 0 < last; last-- ) {		
4				for ( int index = 0; index < last; index++ ) {
5					if ( words[index].compareTo( words[index+1] ) > 0 ) {
						String temp = words[index];
						words[index] = words[index+1];				
6						words[index+1] = temp;						
					}
				}
			}
		
			for ( String word : words ) 
				System.out.print( word + " " );
			scan.close();
7		}
	}