I'm trying to create a Android Hangman app as a bit of self-learning, and so far it's going well, but (typically) the last feature is causing me problems.
So far I have a random word, a timed game, a word by length and now am trying to add on a word by category.
Originally, before the category stage, I have been reading the contents of a text file and using them to populate an ArrayList which a word can be chosen from. Now, as I need a Key:Value pair (category:word) I swapped it out for a Hashmap and check for the next word in the text file that starts with a period "." which donates it to be category. I then use this as the Key and the next bunch of words before the next period "." to be the words.
As, hopefully, some of you may have spotted, this caused a problem in that the Keys have to be unique, so true to hillbilly form, I simply swapped the Key:Value format to be Value:Key... which works great... as a random word.
Note: I had to change the Hashmap for a LinkedHashMap so that I could search by index for a random word at position 'x'.
The problem I have now is that it's a bit hit-and-miss when searching by category. Sometimes it works fine, sometime the wrong category is shown for the word to guess - I don't know why, I've been through the debugger loads of times and it. just. happens?!?!?
Ideally, I would like to be able to return all the words for a given category so that I can pick one from random, but as I say, it's a bit hit and miss whether they're going to match or not.
This is the code I've written for the reading and sorting of the text file:
private String word;
private List<String> words = new ArrayList<>();
private LinkedHashMap<String, String> map = new LinkedHashMap<>();
public List<String> readTextFileAsList(Context ctx, int resId) {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(inputreader);
String line;
String category = null;
try {
//While there are still lines left
while (( line = bufferedreader.readLine()) != null) {
//Add to hash map
if (line.contains(".")) {
//Remove the proceeding period, donating a category
line = line.substring(1, line.length());
//Set the category name to the current line
category = null;
category = line;
} else {
//Add to the hashmap
map.put(line, category);
//Add to the array
words.add(line);
}
}
}
catch (IOException e) {
return null;
}
return words;
}
and I'm currently validating it by searching again if the returned category doesn't match the selected category, like so:
if (!wordBank.getCategory(randomNumber).equals(wordCategorySelected)) {
generateRandomWord(sizeOfWordBank);
}
I have tried this, but to no avail =(
Any help on how I can get this to reliably work would be a great help.
Thanks!