如何解决Java中的NullPointerException错误?

蒙蒂·鲁布(Monty Roob):

我正在用Java做这个非常基本的配置文件创建者,并且在调试时,我一直以NullPointerException错误结束。我不知道如何解决这个问题,如果有人可以告诉我如何解决这个问题,我将不胜感激。这是代码:

import java.util.Scanner;

public class Creator
{
    String[] userNames;
    int[] birthYears;
    String[] genders;
    String userCommand;

    Scanner scanner1 = new Scanner(System.in);
    Scanner scanner2 = new Scanner(System.in);

    public void create()
    {
        System.out.println("What is your name?");
        userNames[0] = scanner1.nextLine();
        System.out.println(userNames[0]);

        System.out.println("In what year were you born?");
        birthYears[0] = scanner1.nextInt();
        System.out.println(birthYears[0]);

        System.out.println("What is your gender?");
        genders[0] = scanner2.nextLine();
        System.out.println(genders[0]);
    }
}

在main方法中,我刚刚创建了一个Creator对象,并使用它来调用method create()该代码永远不会超越“您叫什么名字?” 代码块,每次我运行它都会遇到此错误:

Exception in thread "main" java.lang.NullPointerException
at Creator.create(Creator.java:19)

错误是参考此行:

userNames[0] = scanner1.nextLine();

我不知道如何解决它,如果有人告诉我如何解决它,我将不胜感激。

Chathura Buddhika:

声明数组时,仅创建引用变量。与原始类变量不同,数组在创建对象时不会实例化。要实际创建数组或为数组提供内存,必须创建一个这样的数组。

String[] userNames = new String[5];

否则,您将NullPointerException在尝试访问该数组时进入运行时,因为没有附加实际的数组对象。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章