简体   繁体   中英

null pointer exception in string array with assigning null during initialization

I am beginner in java.Now i'm facing problem during pratice.Actually i want to get String tokens from a StringTokenizer class and wanna assign these tokens to the array of string.but i'm getting null pointer exception.My code is here.

public class Token {
    public static void main(String str[])
    {
        String str1="This is my first page";
        StringTokenizer str2=new StringTokenizer(str1);
        int i=0;
        String d[]=null;
        while(str2.hasMoreTokens())
        {
            d[i]=str2.nextToken();

        }
    System.out.println(d);
    }
}

You should count the token and initialize the string array based on that using str2.countTokens()

And printing should be done inside the loop..

public static void main(String str[]) {
    String str1 = "This is my first page";
    StringTokenizer str2 = new StringTokenizer(str1);
    int i = 0;
    String d[] = new String[str2.countTokens()];
    while (str2.hasMoreTokens()) {
        d[i] = str2.nextToken();
        System.out.println(d[i]);
    }
}

Arrays in Java must be initialized. This:

String d[] = null;

essentially creates a reference to an array, which is null. Hence the NullPointerException .

What is more, even if it were initialized, the size is fixed and the array cannot be resized . You cannot do:

String[] d = new String[]; // won't compile: size not specified

Continuing on, you do:

d[i] = "whatever";

and i is always 0.

Use a List<String> instead:

List<String> list = new ArrayList<>();

and .add(theString) to it:

while (str2.hasMoreTokens())
    list.add(str2.nextToken());

Last but not least, this:

System.out.println(d);

will not do what you think it does. It will print the string representation of the array reference . If you want a string representation of the array plus its elements, do:

System.out.println(Arrays.toString(d));

Trying to populate a null array is unacceptable:

String d[]=null;

Change it to String[] d = new String[20]; , but here is another problem, you don't know how many tokens you will get, so using a dynamic list (eg ArrayList ) will be finer.

Better use a List in you case because u don't know how many Elements the tokenizer returns.

public static void main(String str[])
{
    String str1="This is my first page";
    StringTokenizer str2=new StringTokenizer(str1);
    int i=0;
    List<String> d=new ArrayList<String>();
    while(str2.hasMoreTokens())
    {
        d.add(str2.nextToken());

    }
    System.out.println(d);
}

使用令牌计数进行数组初始化:

String d[]=new String[str2.countTokens()];

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

The following example illustrates how the String.split method can be used to break up a string into its basic tokens:

     String[] result = "this is a test".split("\\s");
     for (int x=0; x<result.length; x++)
         System.out.println(result[x]);

You define d[] as null , and then access element i . That is causing the NullPointerException .

What you should do is initialize d[] big enough for all your tokens to fit, for example String d[] = new String[100] .

Oh, and don't forget to increment your counter i .

Instead of using an array, consider using a List<String> , as it will dynamically increase so you won't have to pick an initial size that is big enough for all your data to fit in.

试试这个数组初始化

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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