基本上我正在尝试编写一个程序,该程序将捕获用户输入并与已定义数组的内容进行比较。如果用户输入正确,那么他将为每个单词获得一分。如果不这样做,生命数量就会减少。我有两个问题:
1)即使输入“你好,我的名字是”,发现似乎也解决了错误问题,因为每次我单击得分按钮时,我输入的每个单词的生命都会减少。
2)我如何以用户需要键入代码才能获得分数的方式实现我的代码,而不是键入“我的你好是名字”,因为这是正确的?因为每个数组中都有匹配的元素。
我的代码是:
Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
final EditText editText = (EditText) findViewById(R.id.user_input);
String[] user_text;
String[] text = {"Hello, my, name, is"};
public void onClick(View v) {
int points = 0;
int lives = 4;
String s = editText.getText().toString();
user_text = s.split("\\s+");
for (int i = 0; i < user_text.length; i++) {
user_text[i] = user_text[i].replaceAll("[^\\w]", "");
}
for (int i = 0; i < user_text.length; i++) {
boolean found = false;
for (int j = 0; j < text.length; j++) {
if ((user_text[i].equals(text[j]))) {
found = true;
break;
}
if (found) {
points++;
}
else {
lives--;
}
}
score_view = (TextView) findViewById(R.id.score);
score_view.setText("score: " + points + "\n lives: " + lives );
}
});
最佳答案
据我了解,您正在尝试匹配两个数组。 这是修改后的代码以实现数组匹配。
boolean found = true;
for (int i = 0; i < user_text.length && i<text.length; i++) {
if (!(user_text[i].equals(text[i]))) {
found = false;
break;
}
}
if (found) {
points++;
}
else {
lives--;
}
关于java - 将用户输入的句子中的每个单词与另一个文本进行比较(android/java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34572592/