您如何使用一组随机给定字母,检查是否仅用给定字母创建一个单词



在java中,我应该做一个单词游戏,应该用给定的一组随机字母制作字母。我已经编写了代码来查找字母(变量是String Letters),但是我在检查玩家选择的单词(String word)是否实际上是使用给定字母创建的吗?我有一个用英语单词的所有英语单词的txt文件,如果它是一个单词,这就是我将其删除的内容。我该怎么做呢?我很确定这与检查索引或使用内置命令包含在。

我已经尝试搜索此问题。但是,其他问题使用了C语言或Python。我找到了1个Java说明,但是我是编码的新手,不了解它们使用的代码和变量。

这是我需要帮助的一个示例

            if (Words.contains(letters) == true) {
            System.out.println("That is a word");
            for (int i = 0; i < word.length(); i++) {
                int index = letters.indexOf(word.charAt(i));
            }

完整方法。

  public static void getWord(String letters) {
    int trys = 0;
    int trysLeft = 5;
    System.out.println("Input a word that you can make with those letters");

    while (trys < 5) {
        String word = getString(); //getString is a method where user can input a desired string
        if (Words.contains(letters) == true) {
            System.out.println("That is a word");
            for (int i = 0; i < word.length(); i++) {
                int index = letters.indexOf(word.charAt(i));
            }
        }
        else if (Words.contains(word) == false) {
            System.out.println("That is not a real word! Please enter a word that you can make with these letters.");
            trys++;
            trysLeft=trysLeft-trys;
            System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
        }
        else if (Words.contains(letters) == false) {
            System.out.println("You can not make a word with these letters.");
            trys++;
            trysLeft=trysLeft-trys;
            System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
        }
    }
}

您需要检查每个字母的辅助因素。如果您发送charseq,示例{'a','b','d'},Java将尝试查找您的字符串是否完全包含" ABD"

做到这一点的一种方法是对字母列表中的字母和单词进行排序,看看您的单词是否包含在可用的字母中,例如:

public static void main(String args[]) {
    String letters = sort("haat");
    System.out.println("Is a word: " + letters.contains(sort("hat")));
}
public static String sort(String s)
{
    char[] chars = s.toCharArray();
    Arrays.sort(chars);
    return new String(chars);
}

您可以使用许多技术来实现此类项目。这是一个:

  1. 从输入字母中构建Map。地图的钥匙应该是字符,地图的值应该是字母的数量。
  2. 从猜测一词中构建Map。同样,地图的钥匙应该是一个字符,地图的值应该是字母的数量。
  3. 比较地图。如果它们是平等的,则该单词是从输入字母字符串中的字母中构成的。

最新更新