2012-06-03 2 views
2

텍스트 파일을 읽고 해당 텍스트 파일의 고유 단어 집합을 ArrayList에 저장하고 있습니다 (더 나은 구조가 있으면 제안하십시오). 스캐너를 사용하여 텍스트 파일을 스캔하고 다음과 같이 구분 기호를 ""(공백)으로 지정합니다.자바 구분 기호가 단어 건너 뛰기

ArrayList <String> allWords = new ArrayList <String>(); 
    ArrayList <String> Vocabulary = new ArrayList <String>(); 
    int count = 0; 

    Scanner fileScanner = null; 
    try { 
     fileScanner = new Scanner (new File (textFile)); 

    } catch (FileNotFoundException e) { 
     System.out.println (e.getMessage()); 
     System.exit(1); 
    } 

    fileScanner.useDelimiter(" "); 

    while (fileScanner.hasNext()) { 

     allWords.add(fileScanner.next().toLowerCase()); 

     count++; 

     String distinctWord = (fileScanner.next().toLowerCase()); 
     System.out.println (distinctWord.toString()); 

     if (!allWords.contains(distinctWord)) { 

      Vocabulary.add(distinctWord); 

     } 
    } 

따라서 어휘의 내용을 인쇄 한 후에는 모든 단어 뒤에 단어가 건너 뜁니다. 그러므로 예를 들어 다음 텍스트 파일이있는 경우;

인쇄 된 내용은 "게으른 이상 빠른 여우"이며, 다음은 나에게 오류를 제공 "빠른 갈색 여우가 게으른 개 점프";

Exception in thread "main" java.util.NoSuchElementException 
    at java.util.Scanner.throwFor(Unknown Source) 
    at java.util.Scanner.next(Unknown Source) 
    at *java filename*.getWords(NaiveBayesTxtClass.java:82) 
    at *java filename*.main(NaiveBayesTxtClass.java:22) 

아무에게도이 문제를 해결하는 방법에 대한 제안을 주실 수 있습니까? fileScanner.useDelimiter 및 fileScanner.hasNext() 문과 관련이 있다고 생각합니다.

+2

'ArrayList'보다는 ['HashSet'] (http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html)을 사용하십시오. 자동으로 중복을 무시합니다. –

+0

그레그 덕분에 HashSet을 사용하는 것이 훨씬 쉽고 훨씬 더 간단했습니다. 매우 감사. – Triple777er

답변

5

hasNext()를 한 번 확인한 후 Scanner # next()를 두 번 호출하면 next()의 결과 중 하나를 무시합니다.

(1)에서 호출하고 모든 단어
에 추가하고 (2)에서 다시 호출하여 인쇄하십시오.

while (fileScanner.hasNext()) { 

    allWords.add(fileScanner.next().toLowerCase()); // **** (1) 

    count++; 

    String distinctWord = (fileScanner.next().toLowerCase()); // **** (2) 
    System.out.println (distinctWord.toString()); 

    if (!allWords.contains(distinctWord)) { 

     Vocabulary.add(distinctWord); 

    } 
} 

해결 방법 :) (다음 번을 스캐너 # 전화 문자열 변수에 반환 저장 한 후 HashSet의에 변수를 추가하고 변수를 인쇄 할 수 있습니다. 당신은 또한 데이터 구조 요청으로 예 :, 안전

while (fileScanner.hasNext()) { 
    String word = fileScanner.next().toLowerCase(); 
    allWords.add(word); // **** (1) 
    count++; 
    // String distinctWord = (fileScanner.next().toLowerCase()); // **** (2) 
    System.out.println (word); 
    vocabularySet.add(word); // a HashSet 
} 

일반적인 규칙은, 당신은 일대일 Scanner#hasNextXXX() 각 호출에 대한 관계 Scanner#nextXXX()

+0

대단히 감사합니다. 내 문제를 해결했습니다. – Triple777er

+0

@ Triple777er : 환영합니다! –

2

이 있어야합니다, 당신은 할 수 있습니다 :

List<String> allWords = new ArrayList<String>(); 
    SortedSet<String> Vocabulary = new TreeSet<String>(); 
    int count = 0; 

    Scanner fileScanner = null; 
    try { 
     fileScanner = new Scanner(new File(textFile)); 

    } catch (FileNotFoundException e) { 
     System.out.println(e.getMessage()); 
     System.exit(1); 
    } 

    fileScanner.useDelimiter(" "); 

    while (fileScanner.hasNext()) { 
     String word = fileScanner.next().toLowerCase(); 
     allWords.add(word); 
     if (Vocabulary.add(word)) { 
      System.out.print("+ "); 
     } 
     System.out.println(word); 
    } 

변수에서 볼 수 있듯이 변수는 interface (List, SortedSet)로 선언되고 구체적인 클래스로 구현됩니다. 이렇게하면 다시 구현할 수있을뿐만 아니라 함수 매개 변수에 특히 유용합니다.