循环结构给出错误的结果

时间:2012-10-08 20:37:58

标签: android string compare

我正在尝试将我的数据库中的项目与EditText(用户输入)的值进行比较。答案可以有多个答案,分别用','。我首先将它们放入一个字符串中,然后将它们与答案进行比较。 LevenshteinDistance检查答案是好还是好(http://en.wikipedia.org/wiki/Levenshtein_distance#Computing_Levenshtein_distance)。

        userAnswer = etUserAnswer.getText().toString().toLowerCase();
        String[] answers = qAnswer.split(",");

        for (String answer : answers) {
            if (answer.equals(userAnswer)) {
                Toast.makeText(getApplicationContext(), ("Answer Correct"),
                        Toast.LENGTH_SHORT).show();
                tvMessage.setText("You smartass!");
            } else {
                Toast.makeText(getApplicationContext(), ("Wrong"),
                        Toast.LENGTH_SHORT).show();

                points = points - 4;
                String answerGood = answer.toLowerCase();

                LevenshteinDistance lDistance = new LevenshteinDistance();
                int comparisonCheck = lDistance.computeLevenshteinDistance(
                        userAnswer, answerGood);

                if (comparisonCheck == 1) {
                    tvMessage.setText("Almost there, but not quite yet!");

                } else if (comparisonCheck > 1) {
                    tvMessage.setText("Are you serious, totally wrong?!");
                }
            }

        }

假设我在DB中有一个问题的答案如下:树,测试,无线电

我有两个问题

1。当我输入“radi”时,它给了'几乎那里......'这很好。如果我输入“tes”,它也应该给我这个,但它给了我“你是认真的......”这一行。我想它与最后一个比较。

2。每当我输入不正确的内容时,我会得到-12而不是-4。我想这是因为我有三个答案并且它循环了三次......但我不知道我怎么能只计算一次..

任何人都可以在途中帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

假设您不需要知道Levenshtein距离最小的单词,您可以修改循环以找到最小距离;

userAnswer = etUserAnswer.getText().toString().toLowerCase();
String[] answers = qAnswer.split(",");
LevenshteinDistance lDistance = new LevenshteinDistance();
int minDistance = lDistance.computeLevenshteinDistance(
                    userAnswer, answers[0].toLowerCase());

for (int i = 1; i < answers.length; ++i) {
    minDistance = Math.min(minDistance, lDistance.computeLevenshteinDistance(
                    userAnswer, answers[i].toLowerCase()));
}

if (minDistance == 0) {
    // Correct answer...
} else {
    // Wrong answer...
    points -= 4;
    // etc etc...
}