What I'm trying to do is add a substring from a String
to an ArrayList
. basically adding every letter in the string to an index in the ArrayList
. After that i have a print statement just to see if the letters were added to the ArrayList
(thats the second for loop under makearraylisOfChosenWord
). However, when i run this with or without the print statement, it gives me a NullPointerException
. Is it because I'm adding the letters to the arraylist in a wrong way in the first for loop?
thanks for the help
heres the code:
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());
}