比较用户输入的句子中的每个单词与另一个文本(android / java)

时间:2016-01-03 01:51:52

标签: java android arrays string comparator

基本上我试图编写一个程序,程序将捕获用户输入并与已定义的数组的内容进行比较。如果用户输入正确,那么他将为每个单词指定一个点。如果没有,生命数量会减少。我有两个问题:

1)发现即使在"你好我的名字是"输入是因为每次我点击分数按钮,我输入的每个单词的生命都会减少。

2)我如何以一种用户需要输入代码的方式来实现我的代码,以获得一个点而不是输入"我的Hello是名字"那是对的吗?因为每个数组中都有一个元素匹配。

我的代码是:

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 );


 }
 });

1 个答案:

答案 0 :(得分:1)

据我了解,您正在尝试匹配两个阵列。 以下是您修改的代码片段以实现数组匹配。

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--;
}