基本上,我被要求创建一个小写字母游戏,其中用户选择一些元音和辅音,并将它们添加到数组列表中,一旦发生这种情况,我们必须打印出数组列表的内容,例如它可能看起来像这样,[T,S,I,L,Y,A,R,R,A],然后我们提示玩家输入他们认为可以从给定的字符列表中组成的单词。我正在寻找的一些指示是如何确保用户只能使用他们的字符以及如何将他们的答案与字典文件进行比较。到目前为止,我唯一的代码是在我的字典文件中读取。任何帮助将不胜感激。
try {
BufferedReader reader = new BufferedReader(new FileReader("dictionary.txt"));
String line = reader.readLine();
List<String> words = new ArrayList<String>();
while (line != null) {
String[] wordsLine = line.split(" ");
for (String word : wordsLine) {
words.add(word);
}
line = reader.readLine();
}
System.out.println("Here is your board again: " + genString + "\n");
System.out.println("Please enter your answer!\n");
} catch (Exception e) {
System.out.println(e);
}
genString 是我的,字符列表是什么,我仍然需要放置扫描仪以供用户输入。
最佳答案
基本思想是将用户输入的字符放入某个集合中,然后迭代单词的字符并对照该集合进行检查。 最后,如果一切正常,请在字典中查找该单词。
List<Character> charsFromUser = new LinkedList<Character>();
Set<String> dictionary = new HashSet<String>();
boolean illegalCharUsed = false;
boolean done = false;
String wordFromUser = null;
// dictionary = // fill dictionary
// charsFromUser = // get chars from user
// wordFromUser = // get word from user
for (int i = 0, l = wordFromUser.length(); i < l && !illegalCharUsed; ++i) {
char c = wordFromUser.charAt(i);
if (!charsFromUser.contains(c)) {
illegalCharUsed = true;
} else {
charsFromUser.remove(Character.valueOf(c)); // remove this line if
// users may reuse letters
}
}
if (!dictionary.contains(wordFromUser)) {
if (!illegalCharUsed && charsFromUser.isEmpty()) { // isEmpty check if users
// must use all letters
System.out.println("well done");
} else {
System.out.println("you didn't use the correct characters");
}
} else {
System.out.println("not a legal word");
}
关于java - 从数组列表中读取并与输入字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22440141/