我陷入一个问题,我必须在一个字符串数组中分配字符串对象,但是问题是我不知道我将在这个数组中放入多少个字符串对象。



   static String[] decipheredMessage;
   static int pointer=0;

   // in another function i have this code
   if(sentenceFormationFlag==true) {
   // System.out.println(" " + word);  // prints the words after sentence formation
   // add the words to an array of strings
   decipheredMessage[pointer] = new String();
   decipheredMessage[pointer++] = word;
   return true;


我在这里所做的是我声明了一个字符串数组,由于我不知道我的数组将包含多少个字符串,因此我会动态创建字符串对象并将其分配给该数组。

错误

$ java SentenceFormation
武器

Exception in thread "main" java.lang.NullPointerException
at SentenceFormation.makeSentence(SentenceFormation.java:48)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.main(SentenceFormation.java:16)


我不知道为什么我遇到这个问题,任何人都可以帮我解决这个问题。
提前致谢。

最佳答案

动态数组在Java中不起作用。您需要使用collections框架的优秀示例之一。导入java.util.ArrayList

static ArrayList<String> decipheredMessage=new ArrayList<>();;
static int pointer=0;

// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word);  // prints the words after sentence formation
 // add the words to an array of strings
decipheredMessage.add(new String());
decipheredMessage.add(word);
return true;

关于java - 在Java中将对象动态存储在未分配的对象中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18802636/

10-11 23:05
查看更多