方法 x 对于类型 y 是未识别的

The method x is unidentified for type y

所以我试图从一个名为 Lexicon 的 Class 中的单词列表中随机获取一个单词。

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";
        }

    }; 

}

至 class 名为游戏 :

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!!");
        }
    }



}

我收到一条错误消息,指出方法 getWord(int) 对于游戏类型是无法识别的。 它一定是非常简单的东西,但我无法让自己找到错误。一直在尝试 hour.My java 技能,整个夏天都生锈了。任何帮助都会提前 appreciated.Thank 你。

因为 getWord() 定义在 class Lexicon 而不是 class Game .

需要game扩展Lexicon如果你希望它继承功能

public class Game extends Lexicon {
    ...
}

或者使用您拥有的 Lexicon:

RandomWord=randomWord.getWord(n);

函数 getWord 在另一个 class 中。您可以将方法复制到游戏中 class 或尝试调用 Lexicon.getWord() 而不是

嗯,你应该 RandomWord = randomWord.getWord(n),而不仅仅是 RandomWord=getWord(n)

无论如何,我不清楚你为什么这样做。词典可以只是一个字符串列表,而不是隐藏在 class(和一个抽象的!)

中的 switch 语句

有两个问题需要解决,

  1. nextInt 函数永远不会得到 0-9,而是 0-8,请更改此行

    int  n = rand.nextInt(9);
    

    int n = rand.nextInt(10);
    
  2. 游戏中未定义 getWord() Class。您应该从 Lexicon Class 呼叫。我建议您将其更改为静态。这是从

    public String getWord(int index) {
    

    public static String getWord(int index) {
    

    所以你可以直接用

    调用函数
    RandomWord = Lexicon.getWord(n);
    

    通过这种方式,您节省了性能并且还拥有实现函数的正确方法,因为静态逻辑应该始终以这种方式实现。


*备注:与编译或bug无关,但为您变量命名:

private int MaxGuess;
private boolean GameOver;
private String RandomWord;

除非您始终按照 smallCamelToe 约定以小写字母开头,否则一些示例如下:

//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;

并且可以执行以下操作:

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));
}