简单的数学游戏?

时间:2018-11-15 11:19:04

标签: android

我是Android的新手,我想创建一个简单的数学测验。我有一个文本视图,使用下面的代码用随机运算符显示随机问题。我想,用户将输入答案到EditText并使用ImageButton提交答案,我称之为提交答案。我的问题是,我无法通过其他方法来检查Edittext上的用户答案。如何在提交按钮后检查评估答案的用户答案?

公共类MainActivity扩展了AppCompatActivity {

int number1, number2, result;
public EditText answer;
char operator;
ImageButton submitAnswer;
Random rand = new Random();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Random rnd = new Random();
    number1 = rnd.nextInt(100) + 1;
    number2 = rnd.nextInt(100) + 1;
    generateOperator();
    TextView question = findViewById(R.id.questionText);
    question.setText(number1 + " " + operator + " " + number2 + " " + "=" + " " + "?");

}


public int generateOperator() {
    int op = rand.nextInt(3) + 1;
    if (op == 1) {
        operator = '+';
        result = number1+number2;
    } else if (op == 2) {
        operator = '-';
        result= number1-number2;
    } else if (op == 3) {
        operator = '*';
        result = number1+number2;
    }
    return operator;

}

public void submitAnswer(View view) {

                submitAnswer = findViewById(R.id.submitButton);
                submitAnswer.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if ( result == Integer.valueOf(answer.getText().toString())){

                            Toast.makeText(view.getContext(), "Correct",
                                    Toast.LENGTH_SHORT).show();

                        }
                        else
                        {
                            Toast.makeText(view.getContext(), "Wrong",
                                    Toast.LENGTH_SHORT).show();

            }

        }
    });
}

}

1 个答案:

答案 0 :(得分:0)

首先,编辑您的generateOperator()方法以保持答案。

public int generateOperator() {
    int op = rand.nextInt(3) + 1;
    if (op == 1) {
        operator = '+';
        result = number1 + number2;
    } else if (op == 2) {
        operator = '-';
        result = number1 - number2;
    } else if (op == 3) {
        operator = '*';
        result = number1 * number2;
    }
    return operator;

}

然后您可以简单地比较您的结果和用户的答案。

submitAnswer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(result == Integer.valueOf(answer.getText().toString())){
                //Answer is ok.
            }
            else {
                //Some code...
            }
        }
    });