为什么在使用loadstrings时出现NullPointerException异常,但不在普通字符串上? (处理)
问题描述:
新手在这里,为什么在使用loadstrings时出现NullPointerException异常,但不在普通字符串上? (处理)
可能是一个逻辑上的错误是这样,我开始了一组代码,而不class
,然后我试图使用它与相同的结果重做,但现在我不断收到一个NullPointerException
错误在words[i].display();
我在做什么错我的代码?下面是我的代码之前和之后......提前感谢任何人可以帮助!
另外,我试着用正常的字符串或不加载外部文件,它工作正常!为什么我开始使用loadstrings
时有什么不同?
BEFORE:
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++ ;
}
}
和AFTER:
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();
但请记住,words
是null
,所以你不能这样使用它!你如何得到一个非价值的i
指数?你不能!你需要实际初始化words
数组。
如果您正在关注最后一个问题的my classes tutorial,请参阅创建多个实例部分。注意:请尝试正确格式化您的代码(Processing编辑器可以为您自动执行,检查菜单)并使用标准命名约定(变量以小写字母开头,类以大写字母开头,案件信)。现在你的代码很难阅读。
再次感谢您提出我的问题! T^T至少它现在更有意义了!我只需要通过这门课程,因为我需要科学课程才能进入我的教师队伍......编程并不是我的事,但我正在努力去理解它!再次感谢你 –
我终于使错误消失btw –