2014-03-04 34 views
-4

我有這個測試程序,我看到一個NullPointer異常。我需要幫助找出如何解決它,並想知道根本原因。在給定的代碼異常(java)

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); 
    } 

} 

我也嘗試調試它,發現內循環拋出異常。

+1

你能告訴我們一個確切的堆棧跟蹤嗎? – GreySwordz

+1

爲了將來的參考,請隨時提供**堆棧跟蹤**,以便您詢問有關錯誤/異常情況。 –

+0

討厭這個downvoting .. !! – Gurjit

回答

5

已分配:

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

,你提到的:

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

由於vowel陣列null,這就是爲什麼你會得到一個NPE。

爲了解決這個問題,你需要將vowel陣列與一個非空值分配:

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

但我分配它的價值,然後..!元音[j]; – Gurjit

+0

值得一提的輔音:) – christopher

+1

@Gurjit你不能**使用陣列,直到你創建它。 'char [] chars = new char [10];'。 – christopher

1

您應該元音輔音和分配內存,否則他們是零。你可以是這樣做的:

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

如果你不知道你應該使用多少內存分配爲您的變量,你可以使用ArrayList這可能全自動分配內存。用以下代碼替換上面的兩行:

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

並將字符添加到兩個列表中。這兩條線

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

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

變化

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

因爲intialising這兩個數組與空值的,你得到NPE:你可以這樣做。

0

你初始化兩個數組的方式是錯誤的!

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

您必須爲非空值賦予元音和輔音的空間。