2017-07-18 18 views
-1

初心者ここでは、おそらくloadstringsを使用していても通常の文字列では使用されていない場合、なぜNullPointerExceptionがありますか? (処理)

ので、論理エラー、私はclassせずにコードのセットで開始し、その後、私は同じ結果でそれを使用することによって、それをやり直してみましたが、今はNullPointerExceptionエラーを得続けますon 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 

    } 


    } 

答えて

0

あなたがここにあなたのwords配列を宣言:

word [] words; 

をこの時点で、wordsは、任意の値を持っていません。 。つまり、nullという値です。

words[i].display(); 

しかし、あなたはこのようにそれを使用することはできませんので、wordsnullであることを覚えておいてください:

は、その後、あなたはここでその変数を使用してみてください! iの価値のないインデックスを取得するにはどうすればよいですか?できません!

実際にwords配列を何かに初期化する必要があります。

最後の質問からmy classes tutorialをフォローしている場合は多くのインスタンスを作成セクションをご覧ください。

サイドノート:コードを適切にフォーマットしてください(Processingエディタは自動的にそれを行い、メニューをチェックします)。標準命名規則を使用します(変数は小文字で始まり、ケースの手紙)。今すぐあなたのコードは読みにくいです。

+0

もう一度質問をしてくれてありがとう! T^T少なくともそれはもうちょっと意味が分かりました!私は私の教員に入るために科学コースが必要なので、このコースを通過する必要があります...プログラミングは本当に私のものではありませんが、私はそれを理解しようとしています!もう一度ありがとうございます –

+0

私はついにエラーを消しましたbtw –

関連する問題