I've written a main method for it also, but I can't tell the source of the error. This is the code I'm using:
import java.io.*;
import java.util.*;
public class WordList{
private ArrayList<String> words;
public WordList(String filename){
ArrayList<String> words = new ArrayList<String>();
}
public ArrayList<String> openFile(String filename) throws IOException{
FileReader fr= new FileReader(filename);
//create a Filereader object
BufferedReader textReader= new BufferedReader(fr);
//create a BR object
String line = textReader.readLine();
while (textReader.readLine() != null){
words.add(line);
textReader.readLine();
}
textReader.close();
return words;
}
Random r= new Random();
public String getRandomWord(){
String x= new String();
int y=r.nextInt(words.size());
x= words.get(y);
return x;
}
}
This is the main method I used for testing my code:
import java.io.*;
import java.util.*;
public class Test{
public void main(String args[])throws IOException{
String path= "C:/Users/Cyril/Desktop/COMP 202/Assignment 4/Text files/Majors.txt" ;
try {
WordList list = new WordList(path);
ArrayList<String> majors = new ArrayList<String>();
majors = list.openFile(path);
System.out.println(majors);
}
catch (IOException e){
System.out.println( e.getMessage());
}
}
}
I am getting a null pointer error. I can't find the source of it. The question I had was:
Write a class WordList with a private arraylist that reads a textfile and stores every line as an entry in the arraylist. I've added the random method to generate random words from the arraylist.