2014-11-20 5 views
0

매우 많은 양의 단어 파일을 가져 와서 특정 길이의 단어를 찾아서 인쇄하는 방법을 쓰려고합니다. 나는 코드를 찾고있는 것이 아니라, 내가 성취하고자하는 것을 정확히 이해하고 있는지 명확하게 설명합니다.텍스트 파일 가져 오기 및 배열 배증

public static void name(int size) throws Exception{ 
Scanner inputFile = new Scanner(new File("2of12inf.txt")); 

그리고 새로운 배열 목록 작성 :

int[] list = new int[MAX_SIZE]; //MAX_SIZE is initially a small number, say 100 
int listSize = 0; 
을 그래서

, 내가 던져 예외를 사용하여 텍스트를 가져, 특정 단어의 문자 수를 걸릴거야

여기서 단어 목록의 크기가 MAX_SIZE 배열을 초과하는 경우 기존 배열을 복사하여 두 배로 늘려 단어 수가 목록에 맞도록 할 것입니다.

if (listSize == list.length) 
{ 
    int[] temp = new int [2*list.length]; 
    for(int i = 0; i < list.length; i++){ 
    temp[i] = list[i];} 
    list = temp; 
} 
list[listSize] = size; 
listSize++; 

inputFile.close();} 

이것은 내가 방법을 쓸 생각 해요 어떻게 내 원시 이해, 이것은 단지 단어를 읽고 그 목록을 제공 할 수있는 올바른 생각이다?

편집 : 죄송 합니다만, ArrayLists를 사용하지 않는다고 언급하지 않았습니다.

+1

당신이'ArrayList'를 사용할 수없는 이유가 있습니까? 또한 왜 필요한 단어 크기가 아닌 단어를 저장합니까? –

+0

왜 이미 정의 된 동적으로 할당 된 ArrayList를 사용하지 않을까요? 예 : ArrayList list = new ArrayList (); ' –

+0

@AlexanderKohler 죄송 합니다만, 방금 ArrayList를 사용하지 않는다고 추가했습니다. 불행히도, 나는 그것을 다른 방식으로해야만하고, 이것이 올바른 생각인지 궁금합니다. – hello

답변

0

프로그램을 실행하기 전에 어느 정도의 길이를 알고 있다면 단어를 반복하면서 단어를 저장하면됩니다. 이처럼

는 말은 :

import java.io.BufferedReader; 
import java.io.FileInputStream; 
import java.io.InputStreamReader; 
import java.util.SortedSet; 
import java.util.TreeSet; 

public class WordLengthPrinter { 
    public static void main(String[] args) throws Exception { 
     if (args.length != 2) 
      throw new IllegalArgumentException("Specify filename as first parameter. Word length is second."); 

     final String fileName = args[0]; // file name is first input argument 
     final int wordLength = Integer.parseInt(args[1]); // the desired wordlength is second argument 

     // lets store the words of correct size in a sorted set 
     SortedSet<String> wordsOfDesiredLength = new TreeSet<String>(); 

     // read file line by line while checking word lengths and only store words of correct length 
     try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) { 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       if (line.length() == wordLength) wordsOfDesiredLength.add(line); 
      } 
     } 

     // print resulting words 
     for (String word : wordsOfDesiredLength) { 
      System.out.println(word); 
     } 
    } 
} 
관련 문제