繁体   English   中英

当我尝试使用整数值填充TextView时,为什么我的应用程序崩溃?

[英]Why does my app crash when i try to populate a TextView with an integer value?

我正在尝试开发一个将用户输入的数字与计算机上随机生成的数字进行比较的应用程序,具体取决于输入数字是更高,更低还是与生成的数字相同,因此会有不同的消息输出。 但是,每当我尝试运行该应用程序时, 应用程序就会崩溃(带有 stacktrace)。 这是我的方法的代码:

如果有人能认出崩溃的原因,那就太好了-Android的新手,所以很难看到错误。

public void guessingGame (View v)
{
    EditText guess = (EditText) findViewById(R.id.ETguess);
    TextView guessError = (TextView) findViewById(R.id.guessError);
    TextView compGuess = (TextView) findViewById(R.id.tvCompGuess);

    int guessValue = Integer.parseInt(guess.getText().toString());

    if (guessValue > 20)
    {
        guessError.setVisibility(View.VISIBLE);
        guess.getText().clear();
    }
    else if (guessValue < 1)
    {
        guessError.setVisibility(View.VISIBLE);
        guess.getText().clear();
    }
    else 
    {
        int min = 1;
        int max = 20;

        Random r = new Random();
        int i = r.nextInt(max - min + 1) + min;

        int computerNumber = i;
        compGuess.setText(i);

        if (computerNumber > guessValue)
        {
            guessError.setText("Too low!");
        }
        else if (computerNumber < guessValue)
        {
            guessError.setText("Too high!");
        }
        else if (computerNumber == guessValue)
        {
            guessError.setText("Good Guess!");
        }
    }

}
    compGuess.setText(i);

您不能使用TextView.setText(int)将文本设置为任意整数。 整数必须是字符串的资源ID(通常在res / values / strings.xml中定义,或从上游依赖项之一导入)。

如果要将TextView的内容设置为表示整数的字符串,则应这样做

    compGuess.setText(Integer.toString(i));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM