Java 当我将扫描器的输入读取到ArrayList中时,为什么会出现NullPointerException?

Java 当我将扫描器的输入读取到ArrayList中时,为什么会出现NullPointerException?,java,arraylist,nullpointerexception,java.util.scanner,Java,Arraylist,Nullpointerexception,Java.util.scanner,我想将扫描仪的输入读取到arraylist中。我已经试过了,但我总是得到一个NullPointerException。谁能告诉我为什么 私有静态数组列表allWords; 私有静态整数字; 公共静态void main(字符串[]args){ 扫描仪sc=新的扫描仪(System.in); while(sc.hasNext()) { 字符串s=sc.next(); 所有文字。添加(s); numberOfWords++; } sc.close(); } 公共静态void main(字符串[]arg

我想将扫描仪的输入读取到arraylist中。我已经试过了,但我总是得到一个NullPointerException。谁能告诉我为什么

私有静态数组列表allWords;
私有静态整数字;
公共静态void main(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
while(sc.hasNext())
{
字符串s=sc.next();
所有文字。添加(s);
numberOfWords++;
}
sc.close();
}
公共静态void main(字符串[]args){
allWords=new ArrayList();//添加了一行以创建空ArrayList
扫描仪sc=新的扫描仪(System.in);
while(sc.hasNext())
{
字符串s=sc.next();
所有文字。添加(s);
numberOfWords++;
}
sc.close();
}
公共静态void main(字符串[]args){
allWords=new ArrayList();//添加了一行以创建空ArrayList
扫描仪sc=新的扫描仪(System.in);
while(sc.hasNext())
{
字符串s=sc.next();
所有文字。添加(s);
numberOfWords++;
}
sc.close();
}

您从未初始化
阵列列表:

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();
}
私有静态列表所有单词;
私有静态整数字;
公共静态void main(字符串[]args){
allWords=new ArrayList();//声明变量而不使用“new”进行初始化将抛出空指针
扫描仪sc=新的扫描仪(System.in);
while(sc.hasNext())
{
字符串s=sc.next();
所有文字。添加(s);
numberOfWords++;
}
sc.close();
}

您从未初始化
阵列列表:

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();
}
私有静态列表所有单词;
私有静态整数字;
公共静态void main(字符串[]args){
allWords=new ArrayList();//声明变量而不使用“new”进行初始化将抛出空指针
扫描仪sc=新的扫描仪(System.in);
while(sc.hasNext())
{
字符串s=sc.next();
所有文字。添加(s);
numberOfWords++;
}
sc.close();
}

allWords
未初始化您从未初始化
allWords
,因此它为空。您必须创建一个新的ArrayList并将其分配给
allWords
变量,然后才能对其调用方法。
allWords
未初始化您从未初始化
allWords
,因此它为空。您必须创建一个新的ArrayList并将其分配给
allWords
变量,然后才能对其调用方法。