我也爲它寫了一個主要方法,但是我無法確定錯誤的來源。這是我使用的代碼:空指針錯誤讀取文本文件並將其存儲在一個數組列表中
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;
}
}
這是最主要的方法我用於測試我的代碼:
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());
}
}
}
我得到一個空指針錯誤。我找不到它的來源。 我的問題是:
寫一個類WordList與一個私人arraylist讀取文本文件,並將每一行作爲條目存儲在arraylist中。 我已經添加了隨機方法來從數組列表生成隨機單詞。
你能後的堆棧跟蹤? –
實例應該使用接口,例如列表不是ArrayList。 –
Rob