为什么在使用加载字符串时出现 NullPointerException 而在普通字符串上却没有? (加工)

why is there a NullPointerException when using loadstrings but not on normal string? (Processing)

这里是新手,

可能是一个逻辑错误所以,我从一组没有 class 的代码开始,然后我尝试通过使用它来重做它并得到相同的结果,但现在我不断得到 NullPointerException words[i].display(); 错误 我的代码做错了什么?以下是我之前和之后的代码...提前感谢任何可以提供帮助的人!

此外,我尝试使用普通字符串或不加载外部文件来执行此操作,但效果很好!为什么我一开始使用就得到它 loadstrings 有什么不同吗?

之前:

 String [] allWords;
 int index = 0 ;
 float x;
 float y; 


void setup () {

size (500,500);
background (255); //background : white

String [] lines = loadStrings ("alice_just_text.txt"); //imports the 
external file
String text = join(lines, " "); //make into one long string
allWords = splitTokens (text, ",.?!:-;:()03 "); //splits it by word

x = 100; //where they start 
y = 150; 

}


void draw() {

background (255);

for (int i = 0; i < 50; i++) {  //produces 50 words

  x = x + random (-3,3); //makes the words move or shake
  y = y + random (-3,3); //makes the words move or shake

  int index = int(random(allWords.length));  //random selector of words

  textSize (random(10,80)); //random font sizes
  fill (0); //font color: black
  textAlign (CENTER,CENTER);
  text (allWords[index], x, y, width/2, height/2); 
  println(allWords[index]); 
  index++ ;


 }

}

和之后:

String [] allWords;
word [] words;
int index = 0 ;

void setup () {

size (500,500);
background (255); //background : white
textSize (random(10,80)); //random font size

String [] lines = loadStrings ("alice_just_text.txt"); 
String text = join(lines, " "); //make into one long string
allWords = splitTokens (text, ",.?!:-;:()03 "); //splits it by word

}

void draw() {

background (255);

for (int i = 0; i < 50; i++) {  //produces 50 words
  words[i].display();

  }

}
class word {
float x;
float y; 

word(float x, float y) {
  this.x = x;
  this.y = y;

}

void move() {
 x = 120 + random (-3,3); //variables sets random positions
 y = 130 + random (-3,3); //variables sets random positions
}

void display() {
 int index = int(random(allWords.length));
 fill (0); //font color: black
 textAlign (CENTER,CENTER); //should make it start at the center
 text (allWords[index], x, y, width/2, height/2); //positions

   }


  }

您在此处声明您的 words 数组:

word [] words;

此时,words没有任何价值。换句话说,它有一个 null 值。

然后您尝试在此处使用该变量:

words[i].display();

但是记住wordsnull,不能这样用!你如何获得非值的 i 索引?你不能!

您需要实际初始化您的 words 数组。

如果您正在关注 my classes tutorial 上一个问题,请参阅 创建多个实例 部分。

旁注:请尝试正确格式化您的代码(Processing 编辑器可以自动为您完成,检查菜单)并使用标准命名约定(变量以小写字母开头,类以大写字母开头)。现在您的代码很难阅读。