So I am trying to get a random word from a list of words in a Class called Lexicon.
public abstract class Lexicon {
public String getWord(int index) {
switch (index) {
case 0: return "UNIVERSITY";
case 1: return "COMPUTER";
case 2: return "LAPTOP";
case 3: return "HEADPHONES";
case 4: return "FUZZY";
case 5: return "HOTEL";
case 6: return "KEYHOLE";
case 7: return "TELEPHONE";
case 8: return "PRINTER";
case 9: return "BUILDING";
default: return "Illegal index";
}
};
}
To a class called Game :
import java.util.Random;
public class Game {
private int MaxGuess;
private boolean GameOver;
private String RandomWord;
public Game(int maxGuess, boolean gameOver, Lexicon randomWord) {
super();
MaxGuess = maxGuess;
GameOver = gameOver;
Random rand = new Random();
int n = rand.nextInt(9);
RandomWord=getWord(n);
}
public void Result(boolean GameOver) {
if(GameOver) {
System.out.println("You have won the game!!");
}
else {
System.out.println("You Lost!!");
}
}
}
and I get an error that says Method getWord(int) is unidentified for type Game. It must be something really simple but I cannot get myself to find the mistake. Been trying for like an hour.My java skills got rusty through out Summer. Any help would be appreciated.Thank you in advance.
Two problems are needed to be addressed,
The nextInt function will never get 0-9, but 0-8, please changed this line
int n = rand.nextInt(9);
to
int n = rand.nextInt(10);
The getWord() is not defined in Game Class. You should be calling from the Lexicon Class. And i recommend you to change it to static. which is changed from
public String getWord(int index) {
to
public static String getWord(int index) {
So you can call the function directly with
RandomWord = Lexicon.getWord(n);
In this way, you saved performance and also have the proper way to implement a function as static logic should always be implemented this way.
*Remark: not related to compiling or bugs, but for you variable naming:
private int MaxGuess;
private boolean GameOver;
private String RandomWord;
unless you should always begin with small letter following smallCamelToe convention, some examples are as follow:
//variable
private int maxGuess;
private boolean gameOver;
private String randomWord;
//constant variable
private final int MAX_GUESS = 1;
//static constant variable, usually be used when implementing constant files and import from other classes
public static final boolean GAME_OVER;
and it is ok to implement the following:
public Game(int maxGuess, boolean gameOver) {
super();
maxGuess = maxGuess; //you can use this.maxGuess if compile failed
gameOver = gameOver; //you can use this.gameOver if compile failed
Random rand = new Random();
RandomWord = Lexicon.getWord(rand.nextInt(9));
}