This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                2年前关闭。
            
        

我想在一组单词中选择一个特定的“短”单词,即最多包含三个字符的单词。
对于此示例,如果传递了包含字符串的数组
“玛丽有只小羊羔”
并要求您返回第二个短字,您将返回“ a”。

import java.util.*;
public class Numbers
{
    String[] words = {"Mary", "had" , "a" , "little" , "lamb"};
       int n = 2;
       public String Numbers;
       String[] word;
       {
          int counter = 1;
          int length = 0;
          int count = 0;

          for (int i = 0; i < words.length; i++)
          {
             length = words[i].length();
           if (length <= 3)
           {
              count++;
              **word[count] = words[i];**
           }
          }
          String answer = word[n];
          System.out.println(answer);

       }

}


当我运行代码时,它给了我一个空异常错误,并且我不确定如何解决它。调试器告诉我,它必须对
word [count] = words [i];

我的代码有什么问题?

最佳答案

数组需要初始化。

String[] word = new String[10];

07-24 21:38