2013-12-03 35 views
0

我也爲它寫了一個主要方法,但是我無法確定錯誤的來源。這是我使用的代碼:空指針錯誤讀取文本文件並將其存儲在一個數組列表中

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中。 我已經添加了隨機方法來從數組列表生成隨機單詞。

+0

你能後的堆棧跟蹤? –

+0

實例應該使用接口,例如列表不是ArrayList。 – Rob

回答

0
private ArrayList<String> words; 

public WordList(String filename){ 
ArrayList<String> words = new ArrayList<String>(); 
} 

在這部分代碼中,構造函數正在創建另一個數組列表,並且類(實例變量)中的一個未鏈接到它。

請改變你的代碼:

private ArrayList<String> words; 

public WordList(String filename){ 
this.words = new ArrayList<String>(); 
} 

那麼它應該工作:)

3

你已經宣佈其陰影的實例成員的局部變量

public WordList(String filename){ 
    ArrayList<String> words = new ArrayList<String>(); 
} 

變化

public WordList(String filename){ 
    words = new ArrayList<String>(); 
} 

But also see Kugathasan's answer...which they just deleted.

這個片段

String line = textReader.readLine(); 
while (textReader.readLine() != null){ 
    words.add(line); 
    textReader.readLine(); 
} 

您正在從輸入流中讀取3行。那是你要的嗎?

+0

我試過了,但是錯誤仍然存​​在。 – user3062902

0

您正在構造函數中聲明一個與實例變量同名的局部變量,而不是分配實例變量。
因此,將聲明更改爲您的構造函數中的賦值,就像這樣。

public WordList(String filename){ 
    words = new ArrayList<String>(); 
} 
0

變化

public WordList(String filename) { 
    ArrayList<String> words = new ArrayList<String>(); 
} 

public WordList(String filename) { 
    words = new ArrayList<String>(); 
} 

因爲你已經陰影的實例成員words在構造函數中,words沒有初始化,默認爲nullnull.SomethingNullPointerException

相關問題