因全局变量而导致NullPointerException

时间:2014-07-05 20:46:52

标签: java class global-variables

CharacterCreator Class

import java.util.*;

public class CharacterCreator {
    /*ch = character
     c = create
     g = generate
     q = question
     r = random*/
    private static Scanner in;
    private static CharacterHair chcHair;
    private static CharacterHair chgHair;

    private static String generate = "generate";
    private static String create = "create";

    public static void main(String[] args) {
        System.out
                .println("Welcome to Character Creator! How would you like to create"
                        + " your character today? Type generate or create.");
        in = new Scanner(System.in);
        String answerHold = in.nextLine();
        if (answerHold.equals(generate)) {
            qgCharacter();
        } else if (answerHold.equals(create)) {
            qcCharacter();
        } else {
            return;
        }
    }
    public static void qgCharacter() {
        chgHair = new CharacterHair();
        chgHair.rbodyHair();
    }
    public static void qcCharacter() {
        chcHair = new CharacterHair();
        chcHair.cbodyHair();

    }
}

CharacterHair Class

import java.util.*;

public class CharacterHair {

    private String[] hair;

    private Random random = new Random();
    private Scanner in = new Scanner(System.in);

    CharacterHair() {
        this.hair = bodyHair();
    }

    public String[] getHair() {
        return this.hair;
    }

    public String[] bodyHair() {
        String[] hair = { "black", "red", "purple", "yellow", "brown",
                "orange", "blue", "blonde" };
        return hair;
    }

    public void rbodyHair() {
        int aaa = random.nextInt(hair.length);
        String pHair = hair[aaa];
        System.out.println(pHair);
    }

    public void cbodyHair() {
        System.out.println("Pick one of these: " + Arrays.toString(hair));
        String pHair = in.nextLine();
        Globe.everything[0] = pHair;
    }
}

全局变量类

public class Globe {
    public static String[] everything;

}

当我运行此代码时,输​​入generate时就可以了。它运行平稳,产生随机发色。 但是,当我输入创建时,我可以选择一种头发颜色,但它不会打印出我选择的头发颜色。当我从图片中删除全局变量时,程序会打印出我存储到pHair的任何内容。我希望程序将pHair的值分配给String[] everything

其他问题:  1.我已经阅读了有关java约定的内容,因为我对编程还很新,我想问一下我是否遵循这些约定。  2.当我打印System.out.println("Pick one of these: " + Arrays.toString(hair));时,它打印出来:选择其中一个:[黑色,红色,紫色,黄色,棕色,橙色,蓝色,金色] 有没有办法删除括号?  如果似乎有任何乱序或奇怪的事情请告诉我。

感谢您的时间:D

2 个答案:

答案 0 :(得分:2)

你的是一个微不足道的错误,你永远不会为你的所有String数组构建一个数组!

您需要everything = new String[SOME_LENGTH];某个地方

如果你不这样做,那么一切都是空的。

更重要的是,您需要学习如何调试NPE(NullPointerException)的一般概念。您应仔细检查抛出它的行,找出哪个变量为null,然后追溯到您的代码以查看原因。你会一次又一次地碰到这些,相信我。

接下来,您将想要摆脱所有"全球"变量,并使您的大多数变量和方法非静态。你的设计坏了。

答案 1 :(得分:0)

您正在尝试访问未初始化的阵列。没有初始化>所有<在你的代码中,从而导致NullPointerException。