1

I want to read the input from my scanner into an arraylist. I already tried it but I always got a NullPointerException. Can somebody tell me why?

private static ArrayList<String> allWords;
private static int numberOfWords;

public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext())
        {
            String s = sc.next();
            allWords.add(s);
            numberOfWords++;
        }
        sc.close();
}
Sokrates
  • 11
  • 2
  • 1
    `allWords` not initialized – azro Sep 17 '19 at 20:45
  • 1
    You never initialize `allWords`, so it's null. You have to create a new ArrayList and assign it to the `allWords` variable before you can call methods on it. – Jordan Sep 17 '19 at 20:45

2 Answers2

0
public static void main (String[] args) {
    allWords = new ArrayList<>(); // Added line to create an empty ArrayList
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext())
    {
        String s = sc.next();
        allWords.add(s);
        numberOfWords++;
    }
    sc.close();
}
arcadeblast77
  • 550
  • 2
  • 12
0

You never initialized the ArrayList:

private static List<String> allWords;
private static int numberOfWords;

public static void main (String[] args) {
        allWords = new ArrayList<>();   // Declaring a variable without initializing it with 'new' will throw a null-pointer
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext())
        {
            String s = sc.next();
            allWords.add(s);
            numberOfWords++;
        }
        sc.close();
}