简体   繁体   English

为什么在我的程序中显示null错误? Stringtokenizer到数组

[英]Why is the null error showing in my program; Stringtokenizer to array

This essentially is a small code I'm writting for practice that requires me to use StringTokenizer. 本质上,这是我为练习而编写的一小段代码,需要我使用StringTokenizer。 I've done the same kind of programs before , but now when I store the strings in an array and try to print them it show's a null pointer exception. 之前我已经做过相同类型的程序,但是现在当我将字符串存储在数组中并尝试打印它们时,它显示为空指针异常。 Any help? 有什么帮助吗?

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

You're shadowing the variable m . 您正在阴影变量m Replace 更换

String m[] = new String[numtokens];

with

m = new String[numTokens];

I think because you are shading properties. 我认为是因为您正在着色属性。 You have an array called m into which you are putting tokens in getSent, but display is using the m array defined in the class to which you haven't added anything. 您有一个名为m的数组,您在其中将令牌放入getSent中,但display使用的是在类中定义的m数组,您没有在其中添加任何内容。

Print out the size of m in display, this will show you that you are not adding anything to the property called m. 打印出显示的m的大小,这将表明您没有在名为m的属性中添加任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM