I'm wetting my feet in java, and I've stumbled upon an issue. I suspect there might be already an answer for it, but I'm too much of a novice to know what it is I should be looking for - it also means my terminology might not be correct.
In the following code, I'm trying to create a random choice from an array of words, then use an if-statement to either display or not display the word. The problem is, although the condition of the if-statement is met (either the string "cat" or the string "dog" are obtained), the action displays any of the listed words, instead of either "cat" or "dog"
I suspect that when I use System.out.println(exampleWord()); in line 10, the routine obtains a new value from the array, effectively ignoring the if-statement.
What's the easiest way around this?
import java.util.Random;
public class Phrasing {
String word;
public static void main(String[] args) {
int i = 1;
while (i < 9) {
if ("cat".equals(exampleWord()) || "dog".equals(exampleWord())) {
System.out.println(exampleWord());
i++;
}
}
}
public static String exampleWord() {
String[] listedWords = {"cat", "dog", "horse", "fish", "turtle", "mouse"};
Random random = new Random();
int index = random.nextInt(listedWords.length);
Phrasing wordOutput;
wordOutput = new Phrasing();
wordOutput.word = listedWords[index];
return (wordOutput.word);
}
}