java - Want to randomly choose word from text file and instead printing everything from text file -
i want compiler randomly
choose word text instead of printing text file. right code below printing text file. think there wrong getword
method because when call getword
method main function error
.
public class textfile { protected static scanner file; protected static list<string> words; public textfile(){ words = openfile(); } private list<string> openfile() { //list<string> wordlist = new arraylist<string>(); try { file = new scanner(new file("words.txt")); } catch (filenotfoundexception e) { system.out.println("file not found"); } catch (exception e) { system.out.println("ioexception"); } return words; } public void readfile() throws filenotfoundexception { //arraylist<string> wordlist = new arraylist<string>(); while(file.hasnext()){ string = file.nextline(); //collections.shuffle(words); //string pickword = words.get(1); //string[] = system.out.println(a); } } public void closefile() { file.close(); } public string getword() { random r = new random(words.size()); string randomword = words.get(r.nextint()); //system.out.println(randomword); return randomword; } public static void main(string[] args) throws filenotfoundexception { try { textfile file = new textfile(); file.openfile(); file.readfile(); file.closefile(); } catch (exception e) { system.out.println("ioexception"); } } }
in openfile method retuning "word" variable null assign value variable
the error coming {getword();} because accessing properties of null variable error
public list<string> readfile() throws filenotfoundexception { while(file.hasnext()){ string = file.nextline(); words.add(a); system.out.println(a); } return words; }
inside open file method @ return statement line call "return readfile();" , try ur code\
no need call readfile method inside main method
Comments
Post a Comment