给定代码中的异常(java)

时间:2014-03-04 15:40:54

标签: java nullpointerexception

我有这个测试程序,我看到一个NullPointer异常。我需要帮助找出如何解决它,并想知道根本原因。

public class test {

    private static void practice(String[] words) {

        int vowelPosition = 0;
        int consonantPosition = 0;
        char[] vowel = (char[]) null;
        char[] consonant = (char[]) null;

        for (int i = 0; i < words.length; i++) {
            int currentWordLength = words[i].length();
            for (int j = 0; j < currentWordLength; j++) {
                if (words[i].charAt(j) == 'a' || words[i].charAt(j) == 'e'
                        || words[i].charAt(j) == 'i'
                        || words[i].charAt(j) == 'o'
                        || words[i].charAt(j) == 'u') {
                    consonant[j] = 'n';
                    vowel[j] = words[i].charAt(j);

                    vowelPosition = j;
                    System.out.println(j + "At this position is "
                            + vowel[vowelPosition]);
                } else {
                    vowel[j] = 'n';
                    consonant[j] = words[i].charAt(j);
                    consonantPosition = j;
                    System.out.println(j + " At this position is "
                            + consonant[consonantPosition]);
                }

            }
        }

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] words = { "harpreet" };
        practice(words);
    }

}

我也试过调试它,发现内循环抛出了异常。

4 个答案:

答案 0 :(得分:5)

您已分配:

char[] vowel = (char[])null;

你可以参考:

vowel[j] = words[i].charAt(j);

由于vowel数组是null,这就是您获得NPE的原因。

为了解决这个问题,您需要为vowel数组分配一个非空值:

char[] vowel = new char[100]; //for example

答案 1 :(得分:1)

您应该为元音和辅音分配内存,否则它们为空。你可以这样做:

char[] vowel = (char[])null;
char[] consonant = (char[])null;

如果您不知道应为变量分配多少内存,可以使用可自动分配内存的ArrayList。用以下行替换上面的两行:

ArrayList<Character> vowel = new ArrayList<Character>();
ArrayList<Character> consonant = new ArrayList<Character>();

并将char添加到两个列表中。你可以这样做:

consonant.add('n');
vowel.add(words[i].charAt(j));

答案 2 :(得分:0)

更改这两行

char[] vowel = (char[]) null;
char[] consonant = (char[]) null;

char[] vowel=new char[100];
char[] consonant = new char[100];

因为用空值初始化这两个数组,你得到了NPE。

答案 3 :(得分:0)

初始化两个数组的方式是错误的!

char[] vowel = (char[])null;
char[] consonant = (char[])null;

您必须为元音和辅音指定空间,并使用非空值。