[英]How do you, using a set of random given letters, check if a word is created with only those given letters
在Java中,我應該做一個文字游戲,用一個給定的隨機字母集來制作字母。 我已經寫了代碼來查找字母(變量是String Letters
),但是我在檢查玩家選擇的單詞( String word
)是否真的使用給定的字母創建時遇到了麻煩。 我有一個用英語寫的所有英語單詞的txt文件,如果這是一個單詞,這就是我要依據的內容。 我該怎么做呢? 我很確定這與檢查索引或使用內置命令contains at有關。
我已經嘗試搜索這個。 但是其他問題使用了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);
}
您可以使用多種技術來實現此類項目。 這是一個:
Map
。 映射的鍵應為字符,映射的值應為字母數。 Map
。 同樣,地圖的鍵應該是字符,地圖的值應該是字母數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.