2014-02-07 1 views
0

프로그램의 셸을 바꿀 수 없으므로 최종 목표는 txt 파일의 단어 목록에서 임의의 단어를 선택하는 것입니다. 나는이 많은 시간 동안 여러 차례 스캔을했고, 코드 하나 하나를 거쳐 여러 가지 다른 것들을 시도했지만, 나는 그것을 실행할 때마다, 문제없이 컴파일하지만 출력을 얻지는 못한다. 나도 개인적인 기능에 약간의 출력을 삽입하려했지만 아무 소용이 없었다. 누구든지 내 코드에 무엇이 잘못되었는지 보거나 어떤 일이 일어 났는지 설명 할 수 있습니까?txt 파일에서 임의의 단어를 가져오고 출력이없고 컴파일러 오류가 발생하지 않습니다. java

import java.util.*; 

    class PartOfSpeech 
    { 
     private String[] words; 
     private Random random; 
     private String filename; 

     public PartOfSpeech(String filename) 
     { 
     this.filename = filename; 
     this.read(); 
     } 
     //this picks a random number and uses that number for the index of the array for which to return 
     public String getRandomWord() 
     { 
     int index; 
     index = random.nextInt(this.getCount()); 
     return words[index]; 
     } 
     //this gets a count of how many lines of txt are in the file 
     private int getCount() 
     { 
     Scanner fr = new Scanner(this.filename); 
     int count = 0; 
     while(fr.hasNextLine()) 
     { 
     count++; 
     } 
     return count; 
     } 
     //this creates a scanner and inserts each word from the txt file into an array 
     private void read() 
     { 
     Scanner fr = new Scanner(this.filename); 
     for(int i=0; i<this.getCount(); i++) 
     { 
     words[i] = fr.nextLine(); 
     } 
     } 

     public static void main(String[] args) 
     { 
     PartOfSpeech n = new PartOfSpeech("nouns.txt"); 
     System.out.print(n.getRandomWord()); 
     } 
    } 
+0

'read' 함수를 호출 한 적이 있습니까? –

+0

constructor의 this.read() – amudhan3093

+0

아, 그래,'getCount'가 무엇을 돌려 주는지? –

답변

1

생성자 스캐너 (문자열 소스) 실제로, 당신은 Oracle 설명서에 따르면

new Scanner(new File(fileName)) 
1

필요가 대신 파일 이름으로 치료의 소스 캐릭터 라인의 내용을 분석, 당신은을 사용한다 스캐너에 인수로 new File을 입력하십시오.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

private void read() 
    { 
    Scanner fr = new Scanner(new File(this.filename)); 
    for(int i=0; i<this.getCount(); i++) 
    { 
    words[i] = fr.nextLine(); 
    } 
    } 
질문에 관련없는

,하지만 당신은 정말이 기능을 재 작성에 대해 생각해야 : 당신은 모든 단어를 얻기 위해 파일을 한 번 읽을 때

//this gets a count of how many lines of txt are in the file 
    private int getCount() 
    { 
    Scanner fr = new Scanner(this.filename); 
    int count = 0; 
    while(fr.hasNextLine()) 
    { 
    count++; 
    } 
    return count; 
    } 

, 당신은을 업데이트해야합니다을 파일을 여러 번 다시 열기보다는 카운트 값을 getCount에 입력하십시오. 파일이 변경되면 countwords 안에있는 항목의 양과 다릅니다.

private void read() 
    { 
    Scanner fr = new Scanner(new File(this.filename)); 

    // reloading the file should clear the collection first 
    words.clear() 

    while(fr.hasNextLine()) 
    { 
    words.add(fr.nextLine()); 
    } 
    } 

    private int getCount() 
    { 
    return words.size(); 
    } 

을 그리고 당신은 아마 어디서나 사용할 만 words.length을 사용하지 않다면 완전히 getCount 도랑 수 있습니다

내가 대신 []의 ArrayList를 함께 이런 일에 코드를 리팩토링 것입니다. read 함수를 여러 번 호출 할 때 사이에 단어를 추가 할 수 있으면 콜렉션을 지워야합니다. 그렇지 않으면 이미 있던 줄까지 모든 요소를 ​​건너 뛴 다음 더 많은 요소를 컬렉션에 추가 할 수 있습니다.

1

귀하의 구조를 재검토 해 보시기 바랍니다. 파일에 얼마나 많은 단어가 있는지 모르기 때문에 두 번 이상 반복되는 것을 피하기 위해 고정 된 String[]과 반대로 Collection<String>을 사용해야합니다.

import java.io.File; 
import java.util.Collections; 
import java.util.LinkedList; 
import java.util.List; 
import java.util.Scanner; 

public class PartsOfSpeech { 

    private final List<String> words; 
    private final File file; 

    private int index; 

    public PartsOfSpeech(final String filePath){ 
     words = new LinkedList<>(); 

     file = new File(filePath); 
     read(); 

     Collections.shuffle(words); 
    } 

    private void read(){ 
     try{ 
      final Scanner input = new Scanner(file, "UTF-8"); 
      while(input.hasNextLine()) 
       words.add(input.nextLine()); 
      input.close(); 
     }catch(Exception ex){ 
      ex.printStackTrace(); 
     } 
    } 

    public String getRandomWord(){ 
     if(index == words.size()){ 
      index = 0; 
      Collections.shuffle(words); 
     } 
     return words.isEmpty() ? null : words.get(index++); 
    } 

    public static void main(String[] args){ 
     final PartsOfSpeech pos = new PartsOfSpeech("noun.txt"); 
     System.out.println(pos.getRandomWord()); 
    } 
} 
0
  1. 인스턴스 변수 임의 초기화되지 않은, 당신은 NPE를 얻을 것이다 : 아마도 당신은 뭔가를 시도 할 수 있습니다.
  2. 다른 사람들이 제안한대로 새 파일 (this.filename)을 사용하십시오.
  3. Scanner.next()를 호출하지 않았으므로 getCount 메서드가 무한 루프에 멈추었습니다.
  4. 다른 사람들이 제안한대로 Collections 개체를 사용합니다.
  5. 카운트해야 할 때마다 전체 목록을 반복 할 필요가 없습니다.
  6. 인스턴스 변수를 사용하지 않거나 완전히 사용하지 않는 것이 좋습니다.
0

파일을 한 번만 문자열 목록으로 읽는 것이 좋습니다. count 메소드는 단순히리스트에서 size()를 호출하는 것이다.다음은 파일을 읽고 문자열 목록으로 파싱하는 데 사용할 수있는 메서드입니다.

public List<String> readFile(String filePath) throws IOException { 
    List<String> result = new ArrayList<>(); 
    try (BufferedReader reader = new BufferedReader(
      new InputStreamReader(
        new FileInputStream(filePath)))) { 
     String line; 
     while ((line = reader.readLine()) != null) { 
      result.add(line.replace("\n", "")); 
     } 
    } 

    return result; 
}