Reputation: 199
I'm trying to use BufferedReader
to import strings from a .txt file into an Arraylist
, then using a random method to randomly pick a string inside the Arraylist
.
But whenever I run this code, it gives me a java.lang.NullPointerException
.
What should I do to fix this problem? Thank you in advance.
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
the .txt file in question consists of a few lines of words.
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Random;
public class WordList{
private static ArrayList<String> words =new ArrayList<String>();
public void main(String[] args) throws IOException {
ArrayListCon("Majors.txt");
System.out.println(words);
}
private void ArrayListCon(String filename) throws IOException{
String line;
BufferedReader br = null;
br = new BufferedReader(new FileReader(filename));
while (( line = br.readLine()) != null){
words.add(line);
}
br.close();
}
public static String getRandomWord(){
Random r = new Random();
String randomWord = words.get(r.nextInt(words.size()));
return randomWord;
}
}
Upvotes: 0
Views: 2546
Reputation: 1576
The exception is arising as a result of a bug in both your code and in the DrJava code.
In your code, you need to make your main method static.
In the DrJava code, they need to add a check for Modifier.isStatic(m.getModifiers())
in the JavacCompiler.runCommand method.
Upvotes: 1
Reputation: 5840
After making the following changes, your code worked perfectly for me, and i never saw the null pointer exception error.
1 ) I first made the method main static, as I was getting an error that there was no main method found:
public static void main(String[] args) throws IOException {
2 ) I also made the ArrayListCon method static
private static void ArrayListCon(String filename) throws IOException{
3 ) I made a file called Majors.txt with the contents:
hello
hi
there
my
words
are
cool
4 ) Finally, I just compiled and ran the program, with the following output:
javac WordList.java
java WordList
[hello, hi, there, my, words, are, cool]
I believe the issue is coming up with how you are running the code (edu.rice.cs.drjava.model.compiler.JavacCompiler)
Upvotes: 1