我正在尝试用Java创建像Typer Shark这样的游戏。我在检测用户键入的字符串是否与数组列表中的元素匹配时遇到问题。我试着这样做:
char key = e.getKeyChar();
ArrayList<String> word = new ArrayList<String>();
word.add("hello");
word.add("red");
word.add("blue");
int counter = 0;
for(String temp:word){
for(int i=0; i<temp.length();i++){
if(key==temp.charAt(i))
counter++;
else
break;
}
if(counter==temp.length())
System.out.println("Correct");
}
我不确定自己是否走在正确的轨道上。提前致谢!
编辑:我尝试使用文本字段进行操作,虽然有效,但播放器必须在程序找到数组列表中的匹配项之前按Enter键。我试图找到是否可以匹配键入的单词而不按Enter键(只需使用Java中的keyTyped)。谢谢!答案 0 :(得分:0)
您没有为每个字重置counter
。将其移到外部for
循环内部。你还需要记住以前的字符。
另请考虑使用String.startsWith
。
除了记住以前的字符,您还可以记住之前匹配的字词。 java.util.BitSet
对此非常理想。
重新编辑:假设您正在使用Swing(或AWT),如果您向DocumentListener
的{{1}}添加JTextField
,请在Document
上运行您的代码, insertUpdate
(removeUpdate
表示其他内容),然后您可以忽略changedUpdate
。