我试图使用BufferedReader
将字符串从.txt文件导入到Arraylist
中,然后使用随机方法随机选择Arraylist
中的字符串。
但是,每当我运行这段代码时,它都会给我一个java.lang.NullPointerException
。
我该怎么做才能解决这个问题?提前谢谢你。
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)
所讨论的.txt文件由几行单词组成。
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;
}
}
发布于 2013-11-30 19:41:57
在进行了以下更改之后,您的代码非常适合我,而且我从未见过空指针异常错误。
1)我第一次使方法是静态的,因为我得到了一个错误,没有找到主要的方法:
public static void main(String[] args) throws IOException {
2)对ArrayListCon方法进行了静态化
private static void ArrayListCon(String filename) throws IOException{
3)我创建了一个名为Majors.txt的文件,内容如下:
hello
hi
there
my
words
are
cool
4)最后,我编译并运行了程序,输出如下:
javac WordList.java
java WordList
[hello, hi, there, my, words, are, cool]
我相信问题是如何运行代码(edu.rice.cs.drjava.model.compiler.JavacCompiler)
的。
发布于 2013-11-30 19:57:18
异常是由于您的代码和DrJava代码中的错误而产生的。
在您的代码中,您需要使主方法是静态的。
在DrJava代码中,他们需要在JavacCompiler.runCommand方法中添加对Modifier.isStatic(m.getModifiers())
的检查。
https://stackoverflow.com/questions/20304730
复制相似问题