-3
public void setAns() {

        if("TF".equals(queType)){
           ans.add("True");
           ans.add("False");
        }
        else if("MC".equals(queType)){
            System.out.println("Enter choice 1 of 4");

            String ch1 = StdIn.readLine();
            ans.add(ch1);
            System.out.println("Enter choice 2 of 4");
            String ch2 = StdIn.readLine();
            ans.add(ch2);
            System.out.println("Enter choice 3 of 4");
            String ch3 = StdIn.readLine();
            ans.add(ch3);
            System.out.println("Enter choice 4 of 4");
            String ch4 = StdIn.readLine();
            ans.add(ch4);

        }
        else if("L5".equals(queType)){
            ans.add("1");
            ans.add("2");
            ans.add("3");
            ans.add("4");
            ans.add("5");
        }
    }

ans is an Arraylist . I am trying to add the user's input which is String. When i run it it prints the first message but has an error when i enter the value for "ch1". It basically doesn't read it and it prompts me for a null pointer exception

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
  • Basically, NPE is thrown when you end up with `null.member` or `null[index]`. Since we don't see your full code and there is no full stack trace we can't be sure what is happening, but based on your description it looks like NPE is thrown from `ans.add(ch1)`. Since there is no problem for ArrayList to hold null `ans.add(null)` should work fine which suggests that it is `null.ans(ch1)` which means you didn't initialize `ans` with ArrayList instance. – Pshemo Apr 09 '17 at 22:23

1 Answers1

0

This is almost certainly due to ans not being initialised before add is called. Could you try initialising it before setAns() is called or try declaring it as a local variable, e.g.:

List<String> ans = new ArrayList<>();
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102