[英]Why is the null error showing in my program; Stringtokenizer to array
本質上,這是我為練習而編寫的一小段代碼,需要我使用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();
}
}
我認為是因為您正在着色屬性。 您有一個名為m的數組,您在其中將令牌放入getSent中,但display使用的是在類中定義的m數組,您沒有在其中添加任何內容。
打印出顯示的m的大小,這將表明您沒有在名為m的屬性中添加任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.