我想要做的是將String
的子字符串添加到ArrayList
。基本上將字符串中的每個字母添加到ArrayList
中的索引中。之後,我有一個打印聲明只是爲了看看這些字母是否被添加到ArrayList
(這是makearraylisOfChosenWord
下的第二個循環)。但是,當我使用或不使用打印語句運行時,它會給我一個NullPointerException
。是否因爲我在第一個for循環中以錯誤的方式將字母添加到了ArrayList中? 感謝您的幫助 繼承人的代碼:NullPointerException從字符串添加子串到數組列表
String[] wordList = {"apple", "orange", "strawberry", "banana"};
String chosenWord;
//Make an array list to hold one letter of the chosen word at each index
void makeArrayListOfChosenWord(){
ArrayList<String> lettersOfChosenWord = new ArrayList<String>();
for (int i = 0; i < chosenWord.length(); i++) {
lettersOfChosenWord.add(chosenWord.substring(i, i+1));
}
for (int i = 0; i < lettersOfChosenWord.size(); i++) {
System.out.println((lettersOfChosenWord.get(i)).toString());
}
}
//Let the game pick a random word from the word list
void setRandomWord(){
int wordListLength = wordList.length;
int pickRandomWord = (int) (Math.random() * wordListLength);
String createRandomWord = wordList[pickRandomWord];
chosenWord = createRandomWord;
System.out.printf("the word is %s letters long", chosenWord.length());
}
這兩種方法完全分開 - 它們是如何相關的?如果你能提供一個簡短的但完整的程序來證明問題,那真的很有幫助。 –
實際上,setrandomword從單詞列表中選擇一個隨機單詞,如果你看,實例變量選擇單詞被賦予隨機單詞pick(它在setrandomword方法中,第4行),並且makearraylist方法使用選擇的單詞變量 –
啊,和你。第二種方法*絕對*在第一種方法之前調用?這是一個簡短但完整的程序會清楚表明的事情。如果您要顯示堆棧跟蹤信息,以便知道發生異常的位置,也會有所幫助。 –