2016-02-12 22 views
0

這實質上是一個小的代碼,我正在寫作練習,需要我使用StringTokenizer。我之前做過類似的程序,但現在當我將字符串存儲在數組中並嘗試打印它們時,它顯示出空指針異常。任何幫助?爲什麼在我的程序中顯示空錯誤; Stringtokenizer數組

import java.util.*; 
public class board1 
{ 
    String key; 
    String m[]; 

    //function to accept the sentence 
    void getsent() 
    { 
     Scanner in=new Scanner(System.in); 
     System.out.println("Enter a sentence terminated by'.' or '?'"); 
     String take=in.nextLine(); 
     StringTokenizer taken=new StringTokenizer(take); 
     int numtokens=taken.countTokens(); 
     String m[]=new String[numtokens]; 
     for(int i=0;i<m.length;i++) 
     { 
      m[i]=taken.nextToken(); 
     } 
     for(int i=0;i<m.length;i++) 
     { 
      System.out.print(m[i]); 
     } 
    } 

    // function to display 
    void display() 
    { 
     System.out.println("The words seperately right now are:"); 
     for(int i=0;i<m.length;i++) 
     { 
      System.out.print(m[i]+"\t"); 
      System.out.println(); 
     } 
    } 

    // main to get functions 
    public static void main(String args[]) 
    { 
     board1 ob= new board1(); 
     ob.getsent(); 
     ob.display(); 
    } 
} 

回答

2

你是shadowing變量m。更換

String m[] = new String[numtokens]; 

m = new String[numTokens]; 
+0

謝謝!這幫助了我很多,並將幫助我參加即將到來的決賽! – Sree

0

我想是因爲你的遮光性。您有一個名爲m的數組,您將令牌放入getSent中,但顯示使用的是未在其中添加任何內容的類中定義的m數組。

打印顯示m的大小,這會告訴你,你沒有添加任何東西到名爲m的屬性。

+0

Thankyou :)你們是最棒的! – Sree

相關問題