java - Why aren't my words coming out less than 8 characters? -


public string compword() throws ioexception, classnotfoundexception {     // local constants     final int max_count = 8;      // local variables     bufferedreader reader = new bufferedreader(new filereader("dictionary.txt"));       // create new bufferedreader, looking dictionary.txt     list<string> lines = new arraylist<string>();                                       // new arraylist keep track of lines     string line;                                                                        // current line     random rand = new random();                                                         // new random object     string word;                                                                        // computer's word      /********************* start compword *********************/      // start reading txt file     line = reader.readline();      // while line isn't null     while(line != null)     {         // add line lines list         lines.add(line);          // go next line         line = reader.readline();     }      // set computers word random word in list     word = lines.get(rand.nextint(lines.size()));      if(word.length() > max_count)         compword();      // return computer's word     return word; } 

from understand should returning words less 8 characters? idea doing wrong? if statement should recall compword until word less 8 characters. reason i'm still words 10-15 chars.

look @ code:

if(word.length() > max_count)     compword();  return word; 

if word picked longer limit, you're calling compword recursively - ignoring return value, , returning "too long" word anyway.

personally suggest avoid recursion, , instead use do/while loop:

string word; {     word = lines.get(rand.nextint(lines.size()); } while (word.length() > max_count); return word; 

alternatively, filter earlier while read lines:

while(line != null) {     if (line.length <= max_count) {          lines.add(line);     }     line = reader.readline(); } return lines.get(rand.nextint(lines.size())); 

that way you're picking out of valid lines start with.

note using files.readalllines rather simpler way of reading lines text file, way - , you're not closing file afterwards...


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -