2017-04-21 41 views
-1

我正在学习课程,当我尝试从文本文件加载时遇到异常。从文本文件读取时发生java.lang.NullPointerException

我想存储的ID和问题。

输出应该是:

{285 = Fill in the blank. A Node is generally defined inside another class, making it a(n) ____ class. } 
{37 = How would you rate your programming skills?} 

这是文本文件里:

258 MC 
Question 
Fill in the blank. A Node is generally defined inside another class, making it a(n) ____ class. 
Answer 
Private 
Inner 
Public 
Internal 
Selected 
2 

37 L5 
Question 
How would you rate your programming skills? 
Answer 
Excellent 
Very good 
Good 
Not as good as they should be 
Poor 
Selected 
-1 

public static void main(String[] args) throws IOException { 

try (BufferedReader br = new BufferedReader(new FileReader("questions.txt"))) { 


    Map < Integer, String > map = new HashMap < Integer, String >(); 
    String line = br.readLine(); 


    while (line != null) { 
    String[] temp; 

    temp = line.split(" "); 
    int id = Integer.parseInt(temp[0]); 

    line = br.readLine(); 
    line = br.readLine(); 

    String question = line; 
    line = br.readLine(); 
    line = br.readLine(); 

    while (line.trim() != ("Selected")) { 

    line = br.readLine(); 

    } 

    line = br.readLine(); 
    int selected = Integer.parseInt(line); 
    line = br.readLine(); 

    map.put(id, question); 
    System.out.println(map); 
    } 
} 

} 

运行时我得到的代码:

线程“main”java.lang.NullPointerException中的异常 daos.test.main(test.java:47)C:\ Users \ droop \ Desktop \ DSA \ New folder \ dsaCW2Template \ nbproject \ build-impl.xml :1076:执行此行时出现以下 错误: C:\ Users \ droop \ Desktop \ DSA \ New folder \ dsaCW2Template \ nbproject \ build-impl.xml:830:Java返回:1 BUILD FAILED(total时间:0秒)

回答

3

开始与

while (line.trim() != ("Selected")) { 
    ... 

while循环的条件总是满足,所以你最终阅读关闭文件的末尾。 line最终变成nullline.trim()得到NPE。

千万不要将字符串与==或`!=;使用String.equals()代替:

while (!line.trim().equals("Selected")) { 
    ... 
0

修复你的内心,而条件

while (line != null && line.trim() != ("Selected")) { 

    line = br.readLine(); 

} 

和完善哟你的逻辑获得正确的输出。

+0

ouch。用另一个替换一个错误.... –

相关问题