I decided to incorporate the “vocab” feature into my “Wheel Of Fortune” project. Every time Java guesses a word, that word is added to its vocab (it’s an ArrayList
). That “knowledge” is supposed to make Java better and better at making guesses with each run: if the “current word” matches one of the words it dealt with previously, Java should make appropriate guesses. For example, if the “current word” is “j * v *” (*s stand for letters that are not yet guessed) and it already “knows” the word “java”, the program will likely suggest “a” and “win” the game. My updated method, I believe, would work just the way I envisaged if there was indeed a dynamically updated vocabulary. But I’m not yet adept at serialization/deserialization so I have a compilation error (see the readObject()
method). Could you please take a look at the code and point to the mistake(s) I made?
import java.util.*;
import java.io.*;
public class Wheel implements Serializable {
static ArrayList<String> vocab;
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream fileInputStream = new FileInputStream("vocab.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
vocab = (ArrayList<String>) objectInputStream.readObject();
/* this line, (ArrayList<String>) objectInputStream.readObject();, is highlighted
in yellow: IntelliJ IDEA says this: Unchecked cast: 'java.lang.Object' to
'java.util.ArrayList<java.lang.String>' */
wheelOfFortune("someWordForJavaToGuess");
FileOutputStream fileOutputStream = new FileOutputStream("vocab.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(vocab);
}
public static void wheelOfFortune(String word) {
// the method's machinery
vocab.add(correctWord);
System.out.println("\nI guessed it! It's " + correctWord + "!");
}
public static void writeObject(ObjectOutputStream stream) throws IOException {
stream.writeObject(vocab);
}
public static void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.readObject(vocab);
/* readObject() is underlined in red: IntelliJ IDEA says this:
'readObject(java.lang.Class<?>)' has private access
in 'java.io.ObjectInputStream' */
}
}