[英]Comparing string and text, character by character
我正在做一个打字游戏,当用户输入密钥时,程序应将其与存储的字符串/数组进行比较。 如果它与该索引处的字符匹配,则分数变量应增加。
我试图将输入的文本存储在字符串中,然后将其分解为字符后进行比较。
text=new JTextField(40);
String sentence="the quick brown fox jumps over the lazy dog";
String store=text.getText();
for (int i = 0; i < store.length(); i++) {
if(store[i]==sentence.charAt(i)) { //error
score++;
}
}
如果输入的键与字符匹配,则增加“分数”,否则减小。
您的store
变量也是String而不是数组,因此必须使用.charAt()
:
for (int i = 0; i < Math.min(store.length(), sentence.length()); i++) {
if(store.charAt(i) == sentence.charAt(i)) {
score++;
} else {
score--;
}
}
您还应该使用Math.min(store.length(), sentence.length())
来防止IndexOutOfBoundsException
。
我同意Samuel Philipp使用.charAt().
我想补充一点。 .charAt()
在给定的索引处搜索字符。 根据您的水平,我认为这种方法很适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.