Thread: Hangman Game
View Single Post
  #4 (permalink)  
Old 07-02-2008, 11:45 PM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
It makes more sense to read in all the words only one time and to then access them as needed. Or to read in words until you get to the counter word and return it.
Code:
import java.io.*; import java.util.*; public class WordRx { File myFile; int counter=0; int amountOfWords; List<String> list; public WordRx(File f) { myFile=f; // Call to countWords required for list to be filled. list = new ArrayList<String>(); } public int getAmountOfWords() throws FileNotFoundException, IOException { countWords(); return amountOfWords; } public void countWords() throws FileNotFoundException, IOException { int count=0; FileReader fr=new FileReader(myFile); BufferedReader br=new BufferedReader(fr); String line=br.readLine(); while(line!=null) { StringTokenizer st=new StringTokenizer(line); while(st.hasMoreTokens()) { String word=st.nextToken(); list.add(word); count++; } line=br.readLine(); } amountOfWords=count; } public String nextWord() throws FileNotFoundException, IOException { String nextWord=""; FileReader fr=new FileReader(myFile); BufferedReader br=new BufferedReader(fr); String line=br.readLine(); int count = 0; while(line!=null) { StringTokenizer st=new StringTokenizer(line); while(st.hasMoreTokens()) { nextWord = st.nextToken(); if(count == counter) { counter++; return nextWord; } count++; } line=br.readLine(); } return nextWord; } private String getNextWord() { //if(counter < list.size()) return list.get(counter++); } public static void main(String[] args) throws FileNotFoundException, IOException { String path = "tutorial/dictionary.txt"; File file = new File(path); WordRx test = new WordRx(file); int wordCount = test.getAmountOfWords(); System.out.println("wordCount = " + wordCount); for(int i = 0; i < 10; i++) { System.out.println(test.nextWord()); } for(int i = 0; i < 10; i++) { System.out.println(test.getNextWord()); } } }
Reply With Quote