2010-11-23 9 views
1

나는 끝내기가 거의 끝났지 만, 모든 것을 묶는 방법을 알아낼 수는 없습니다. 나는 그들의 특별한 임무에 대한 책임이있는 별도의 방법을 가지고 있지만, 나의 결속이 실제로 나쁘다고 느낀다. 어떻게 그들이 함께 묶고 무엇이 메인에서 호출되어야하는지 확실하지 않습니다. 여기서 목표는 명령 줄에서 텍스트 파일을 읽고 스토리의 사전 단어를 사전 식으로 나열하는 것입니다. 여기 리스트 정렬에 대한 할당

% java Ten < story.txt 
Word  Occurs 
====  ====== 
a   21 
animal  3 
. 
. 
. 
zebra  1 
% 

는 지금까지 내 코드입니다 :

import java.util.Scanner; 

public class Ten2 
{ 
    public static void main(String [] arg) 
    { 
     Scanner input = new Scanner(System.in); 

     String word; 
     List sortedList = new List(); 
     word = nextWord(input); 

     while (word!=null) { 
      sortedList.insert(word); 
      word = nextWord(input); 
     } 

     sortedList.printWords();   
    } 

    private static String nextWord(Scanner input) 
    { 
     // return null if there are no more words 
     if (input.hasNext() == false) 
      return null; 
     // take next element, convert to lowercase, store in s 
     else { 
      String s = input.next().toLowerCase() ; 
      // empty string 
      String token = ""; 
      // loop through s and concatonate chars onto token 
      for (int i =0; i < s.length(); i++) { 
       if (Character.isLetter(s.charAt(i)) == true) 
        token = token + s.charAt(i); 
       else if (s.charAt(i) == '\'') 
        token = token + s.charAt(i); 
       else if (s.charAt(i) == '-') 
        token = token + s.charAt(i); 
      } 
      return token; 
     }  
    } 
} 

class List 
{ 
    /* 
    * Internally, the list of strings is represented by a linked chain 
    * of nodes belonging to the class ListNode. The strings are stored 
    * in lexicographical order. 
    */ 
    private static class ListNode 
    { 
     // instance variables for ListNode objects 
     public String word; 
     public ListNode next; 
     public int count; 

     // Listnode constructor    
     public ListNode(String w, ListNode nxt) 
     { 
      word = w; // token from nextWord()? 
      next = nxt; // link to next ListNode 
      count = 1; // number of word occurences 
     } 
    } 

    // instance variables for List object 
    private ListNode first; 
    private int numWords; 

    // constructor postcondition: creates new Listnode storing object 
    public List() 
    { 
     first = null; // pointer to ListNode? 
     numWords = 0; // counter for nodes in list 
    } 


    // Insert a specified word into the list, keeping the list 
    // in lexicographical order. 
    public void insert(String word) 
    {  
     // check if first is null 
     if (first == null) { 
      ListNode newNode; 
      newNode = addNode(word, null); 
      first = newNode;   
     } 

     // else if (first is not null) check if word matches first word in List 
     else if (word.equals(first.word)) { 
      // increase count 
      first.count++; 
      } 

     // else (first is not null && doesn't match first word) 
     else { 
      ListNode newNode; 
      ListNode current; 
      current = first; 
      ListNode previous; 
      previous = null; 
      int cmp = word.compareTo(current.word); 

      /* 
      * Fist two cases of empty list and word already existing 
      * handled in above if and else statements, now by using compareTo() 
      * method between the words, the insertion postion can be determined. 
      * Links between ListNode variables current and previous need to be 
      * modified in order to maintain the list 
      */ 


      // loop as long as value comparing to is positive 
      // when compareTo() returns positive this means the "word" parameter is greater than the word in the list 
      while ((cmp >0) && (current.next != null)) { 
       previous = current;  
       current = current.next; 
       cmp = word.compareTo(current.word); 
      } 

      // insert after current at end of list 
      if ((cmp >0 && current.next == null)) { 
       newNode = addNode(word, null); 
       current.next = newNode; 
      } 

      // increments count when word already exists 
      else if (cmp==0) { 
       current.count++; 
      } 

      // else (cmp < 0) we insert BEFORE current 
      else { 
       newNode = addNode(word, current); 

       // first node in list comes after new word 
       if (previous == null) { 
        first = newNode;  
       }   

       else { 
        // inserting new word in middle of list 
        previous.next = newNode; 
       } 
      }  
     } 
    } 

    // method to add new ListNode and increase counter 
    private ListNode addNode(String word, ListNode next) 
    { 
     ListNode newNode = new ListNode(word, next); 
     numWords++; 
     return newNode; 
    } 


    // Returns a string array that contains all the words in the list. 
    public String[] getWords() 
    { 
     String[] Words = new String[numWords]; 
     ListNode current = first; 
     int i =0; 

     while (current != null) {  
      Words[i] = current.word; 
      current = current.next; 
      i++; 
     } 
     return Words; 
    } 


    // Returns an int array that contains the number of times 
    // each word occurs in the list. 
    public int[] getNumbers() 
    { 
     int[] Numbers = new int[numWords]; 
     ListNode current = first; 
     int i =0; 

     while (current != null) { 
      Numbers[i] = current.count; 
      current = current.next; 
      i++; 
     } 
     return Numbers; 
    } 


    // Outputs the string array and int array containing all the 
    // words in the list and the number of times each occurs. 
    public void printWords() 
    { 
     int[] Numbers = getNumbers(); 
     String[] Words = getWords(); 

     System.out.println("Word \t \t Occurs"); 
     System.out.println("==== \t \t ======"); 

     for (int i =0; i < numWords; i++) { 
      System.out.println(Words[i] + " \t " + Numbers[i]); 
     } 
    }  
} 

답변

3

를 글쎄, 난 당신이 이미 완료 한 할 수있는 프로그램, 원하는 것을 정의하여 시작합니다 :

목표를 여기에 명령 줄에서 텍스트 파일을 읽고 이야기의 단어를 사 전적으로 나열합니다.

당신은이 기능을 수행합니다. 거의입니다. 기본적으로, 당신이 필요로하는 것은 묶어 둘 고리입니다 :

public static void main(String [] arg) 
{ 
    // print out your initial information first (i.e. your column headers) 
    // ... 

    List sortedList = new List(); 
    String word = nextWord(); 

    // now, the question is... what is the end condition of the loop? 
    // probably that there aren't any more words, so word in this case 
    // will be null 
    while (word != null) 
    { 
     sortedList.insert(word); 
     word = nextWord(); 
    } 

    // now, your list takes care of the sorting, so let's just print the list 
    sortedList.printWords(); 
} 

나는 그게 전부라고 생각합니다. 일반적으로 나는 숙제에 대한 해결책을 게시하고 싶지 않지만,이 경우에는 이미 모든 코드가 있었기 때문에 올바른 방향으로 운전할 수있는 약간의 지식이 필요했기 때문에 괜찮다고 생각합니다.

에 잘못된 내가 눈치 몇 가지가있다 당신의

귀하의 목록에 생성자는 '무효'반환 형식이 - 생성자에는 반환 형식이 없어야합니다 :

public List() //make an empty list 
{ 
    first = null; 
    numWords = 0; 
} 

'다른 사람을 '이 방법의 문은 불필요한입니다 :

public static String nextWord() 
    { 
     if (keyboard.hasNext() == false) 
      return null; 
     else { 
      String start = keyboard.next().toLowerCase() ; 
      String organized = ""; 
      for (int i =0; i < start.length(); i++) { 
       if (Character.isLetter(start.charAt(i)) == true) 
        organized = organized + start.charAt(i); 

       else if (start.charAt(i) == '\'') 
        organized = organized + start.charAt(i); 

       else if (start.charAt(i) == '-') 
        organized = organized + start.charAt(i); 
      } 
      return organized;  
     } 
    } 

그래서,이 있어야한다 :

public static String nextWord() 
{ 
    if (keyboard.hasNext() == false) 
     return null; 
    String start = keyboard.next().toLowerCase() ; 
    String organized = ""; 
    for (int i =0; i < start.length(); i++) { 
     if (Character.isLetter(start.charAt(i)) == true) 
      organized = organized + start.charAt(i); 

     else if (start.charAt(i) == '\'') 
      organized = organized + start.charAt(i); 

     else if (start.charAt(i) == '-') 
      organized = organized + start.charAt(i); 
    } 
    return organized; 
} 

BufferedReader를 사용하려는 경우 매우 쉽습니다. 스캐너 객체 설정하는 새로운 방법을 만들고, 그런 다음

if (arg.length > 0) 
    { 
    // open our file and read everything into a string buffer 
    BufferedReader bRead = null; 
    try { 
     bRead = new BufferedReader(new FileReader(arg[0])); 
    } catch(FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     System.exit(0); 
    } 
    setupScanner(bRead); 
    } 

: : 그냥 기본 방법을 설정 단지 명령 행에서 그것을에서 통과 한 후

public static void setupScanner(BufferedReader rdr) 
{ 
    keyboard = new Scanner(rdr); 
} 

그리고 (즉 자바 ten2 [파일 이름])

+0

또한 빠른 참조 - 아마도 조금 다르게했을 것입니다. 사용자가 * filename *을 인수로 지정한 다음 BufferedReader를 열면 좋겠지 만 스타일 문제가 더 많을 것으로 생각됩니다. :) – jwir3

+0

도움을 주셔서 감사합니다. 내 인쇄 방법에서 컴파일러 오류가 발생했습니다. getWords() 및 getNumbers()에서 "List"참조를 삭제했습니다. 이제 컴파일되지만, main에서 .txt 파일에 대한 테스트를 실행하는 방법을 정확하게 모르겠습니다. 나는 BlueJ를 사용하고 출력을 보는 방법을 모르고있다. JVM은 계속 실행됩니다. – Bill

+0

흠 ... 전 BlueJ를 IDE로 사용한 적이 없습니다. 나는 Eclipse를 실제로 추천 할 것이다. 당신이 할 수있는 다른 일은 BlueJ를 사용하여 컴파일 한 다음, 터미널을 사용하여 프로젝트 디렉토리에서 클래스/디렉토리로 이동합니다 (사용중인 OS에 따라 Windows cmd 또는 터미널 만 사용). 그런 다음 java Ten2 jwir3

0
import java.util.Scanner; 

public class Ten2 
{ 
    public static void main(String [] arg) 
    { 
     Scanner input = new Scanner(System.in); 

     String word; 
     List sortedList = new List(); 
     word = nextWord(input); 

     while (word!=null) { 
      sortedList.insert(word); 
      word = nextWord(input); 
     } 

     sortedList.printWords();   
    } 

    private static String nextWord(Scanner input) 
    { 
     // return null if there are no more words 
     if (input.hasNext() == false) 
      return null; 
     // take next element, convert to lowercase, store in s 
     else { 
      String s = input.next().toLowerCase() ; 
      // empty string 
      String token = ""; 
      // loop through s and concatonate chars onto token 
      for (int i =0; i < s.length(); i++) { 
       if (Character.isLetter(s.charAt(i)) == true) 
        token = token + s.charAt(i); 
       else if (s.charAt(i) == '\'') 
        token = token + s.charAt(i); 
       else if (s.charAt(i) == '-') 
        token = token + s.charAt(i); 
      } 
      return token; 
     }  
    } 
} 

class List 
{ 
    /* 
    * Internally, the list of strings is represented by a linked chain 
    * of nodes belonging to the class ListNode. The strings are stored 
    * in lexicographical order. 
    */ 
    private static class ListNode 
    { 
     // instance variables for ListNode objects 
     public String word; 
     public ListNode next; 
     public int count; 

     // Listnode constructor    
     public ListNode(String w, ListNode nxt) 
     { 
      word = w; // token from nextWord()? 
      next = nxt; // link to next ListNode 
      count = 1; // number of word occurences 
     } 
    } 

    // instance variables for List object 
    private ListNode first; 
    private int numWords; 

    // constructor postcondition: creates new Listnode storing object 
    public List() 
    { 
     first = null; // pointer to ListNode? 
     numWords = 0; // counter for nodes in list 
    } 


    // Insert a specified word into the list, keeping the list 
    // in lexicographical order. 
    public void insert(String word) 
    {  
     // check if first is null 
     if (first == null) { 
      ListNode newNode; 
      newNode = addNode(word, null); 
      first = newNode;   
     } 

     // else if (first is not null) check if word matches first word in List 
     else if (word.equals(first.word)) { 
      // increase count 
      first.count++; 
      } 

     // else (first is not null && doesn't match first word) 
     else { 
      ListNode newNode; 
      ListNode current; 
      current = first; 
      ListNode previous; 
      previous = null; 
      int cmp = word.compareTo(current.word); 

      /* 
      * Fist two cases of empty list and word already existing 
      * handled in above if and else statements, now by using compareTo() 
      * method between the words, the insertion postion can be determined. 
      * Links between ListNode variables current and previous need to be 
      * modified in order to maintain the list 
      */ 


      // loop as long as value comparing to is positive 
      // when compareTo() returns positive this means the "word" parameter is greater than the word in the list 
      while ((cmp >0) && (current.next != null)) { 
       previous = current;  
       current = current.next; 
       cmp = word.compareTo(current.word); 
      } 

      // insert after current at end of list 
      if ((cmp >0 && current.next == null)) { 
       newNode = addNode(word, null); 
       current.next = newNode; 
      } 

      // increments count when word already exists 
      else if (cmp==0) { 
       current.count++; 
      } 

      // else (cmp < 0) we insert BEFORE current 
      else { 
       newNode = addNode(word, current); 

       // first node in list comes after new word 
       if (previous == null) { 
        first = newNode;  
       }   

       else { 
        // inserting new word in middle of list 
        previous.next = newNode; 
       } 
      }  
     } 
    } 

    // method to add new ListNode and increase counter 
    private ListNode addNode(String word, ListNode next) 
    { 
     ListNode newNode = new ListNode(word, next); 
     numWords++; 
     return newNode; 
    } 


    // Returns a string array that contains all the words in the list. 
    public String[] getWords() 
    { 
     String[] Words = new String[numWords]; 
     ListNode current = first; 
     int i =0; 

     while (current != null) {  
      Words[i] = current.word; 
      current = current.next; 
      i++; 
     } 
     return Words; 
    } 


    // Returns an int array that contains the number of times 
    // each word occurs in the list. 
    public int[] getNumbers() 
    { 
     int[] Numbers = new int[numWords]; 
     ListNode current = first; 
     int i =0; 

     while (current != null) { 
      Numbers[i] = current.count; 
      current = current.next; 
      i++; 
     } 
     return Numbers; 
    } 


    // Outputs the string array and int array containing all the 
    // words in the list and the number of times each occurs. 
    public void printWords() 
    { 
     int[] Numbers = getNumbers(); 
     String[] Words = getWords(); 

     System.out.println("Word \t \t Occurs"); 
     System.out.println("==== \t \t ======"); 

     for (int i =0; i < numWords; i++) { 
      System.out.println(Words[i] + " \t " + Numbers[i]); 
     } 
    }  
} 
관련 문제