Sree
Sree

Reputation: 1

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

Upvotes: 0

Views: 72

Answers (2)

Reimeus
Reimeus

Reputation: 159844

You're shadowing the variable m. Replace

String m[] = new String[numtokens];

with

m = new String[numTokens];

Upvotes: 2

Gavin
Gavin

Reputation: 1767

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.

Print out the size of m in display, this will show you that you are not adding anything to the property called m.

Upvotes: 0

Related Questions