java - 从编辑文本中获取值并将其与设置的变量进行比较

标签 java android math

任何人都可以发现我在这里做错了什么吗?当我调用 checkAnswer() 时,它会使程序崩溃。这是变量和我的按钮。

int random1;
int random2;

 int Min = 1;
 int Max = 4;
 int score = 0;
 int correctAnswer;
 String question;

String i;
String a;

  editText = (EditText)findViewById(R.id.Edit);
   editTextEquation = (TextView)findViewById(R.id.equation);
  scoredisplay = (TextView)findViewById(R.id.score);


@Override
public void onClick(View v){
switch(v.getId()){
case R.id.keypad_hash:

    getQuestion();
   checkAnswer(editText.getText().toString());

    break;

我正在尝试提取用户输入编辑文本的值,然后将其与答案进行比较。

 public void getQuestion(){

    random1 = (int)(Math.random()*100);
    random2 = (int)(Math.random()*10);

    int i1 = Min + (int)(Math.random() * ((Max - Min) + 1));

    if(i1 == 1){
    question = (random1 + "+" + random2);
    correctAnswer = random1 + random2;
    editTextEquation.setText(question);
    }
    if(i1 == 2){
    question = (random1 + "-" +random2);
    correctAnswer = random1 - random2;
    editTextEquation.setText(question);

    }
    if(i1 == 3){
    question = random1 + "/" +random2;
    correctAnswer = random1 / random2;
    editTextEquation.setText(question);

    }
    if(i1 == 4){
    question = (random1 + "*" +random2);
    correctAnswer = random1 * random2;
    editTextEquation.setText(question);


    }



}

public void checkAnswer(){
    i = editText.getText().toString();
    Integer a = Integer.valueOf(i);
    if (a == correctAnswer){

        score++;
        scoredisplay.setText(score);

    }
    else{

        score--;
        scoredisplay.setText(score);
    }




}

最佳答案

您应该使用String 调用setText。如果您使用 int 调用它,它会尝试查找与该 id 匹配的字符串。所以可能应该是:

scoredisplay.setText("" + score);

此外,请使用 .equals 比较字符串,而不是 ==,因为 == 比较引用,而不是内容。

关于java - 从编辑文本中获取值并将其与设置的变量进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9588389/

相关文章:

java - 提交表单时出现 Spring 日期转换错误

java - 鉴于我有一个包含文件名的字符串,为什么我不能在 java 中拆分一个字符串?

android - 使用 python 获取 Google Play 商店应用程序下载链接

android - 在各种 Activity 中使用相同的 onTouchEvent

machine-learning - MAPE 损失函数相对于 MAE 和 RMSE 的优势

php - 如何将一个数自乘 X 次?

php - 试图在 PHP 中创建类似于近似子集和表的算法

java 应用程序不在另一台计算机上运行

java - 针对 json 架构的 Json 验证失败

android - android singleTask Activity 不作为root?