-1

I am working on a coursework and I'm facing an exception when I try to load from a text file.

I am trying to store the IDs and the Questions.

The output should be :

{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?} 

This is inside the textfile :

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);
  }
 }

}

When running the code I'm getting :

Exception in thread "main" java.lang.NullPointerException at daos.test.main(test.java:47) C:\Users\droop\Desktop\DSA\New folder\dsaCW2Template\nbproject\build-impl.xml:1076: The following error occurred while executing this line: C:\Users\droop\Desktop\DSA\New folder\dsaCW2Template\nbproject\build-impl.xml:830: Java returned: 1 BUILD FAILED (total time: 0 seconds)

Draken
  • 3,134
  • 13
  • 34
  • 54
Paul
  • 3
  • 1
  • 2

2 Answers2

3

The condition of the while loop beginning with

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

is always met, so you end up reading off the end of the file. line eventually becomes null and line.trim() gets an NPE.

Never compare strings with == or `!=; use String.equals() instead:

while (!line.trim().equals("Selected")) {
    ...
Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21
0

Fix Your inner while condition

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

   line = br.readLine();

}

And improve your logic for getting right output.

Nitish Bhagat
  • 98
  • 1
  • 9