首页 文章

从文本文件中读取时出现java.lang.NullPointerException [重复]

提问于
浏览
-1

这个问题在这里已有答案:

我正在做一个课程,当我尝试从文本文件加载时,我遇到了异常 .

我正在尝试存储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);
  }
 }

}

运行我得到的代码时:

daos.test.main(test.java:47)中的线程“main”java.lang.NullPointerException中的异常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(总时间:0秒)

2 回答

  • 0

    修复你内在的条件

    while (line != null && line.trim() != ("Selected")) {
    
       line = br.readLine();
    
    }
    

    并改善您获得正确输出的逻辑 .

  • 3

    while 循环的条件以 . 开头

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

    总是满足,所以你最终读取文件的末尾 . line 最终变为 nullline.trim() 获得NPE .

    切勿将字符串与 == 或`!=;进行比较使用String.equals()代替:

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

相关问题