我正在尝试创建一个按钮,将TextView中需要的文本放在特定的EditText条件下,当EditText为空时,TextView显示正确的文本,但是当我将数字写入EditText字段并按下按钮时 - 程序崩溃。
public void Guess(View view) {
EditText Spejimas = (EditText) findViewById(R.id.guess);
Tekstas = (TextView) findViewById(R.id.textView3);
if (Spejimas.getText().length() == 0) {
Tekstas.setText("Oops, you forgot to type your guess!");
} else if (Spejimas.getText().length() != 0) {
int Guessas = Integer.parseInt(Spejimas.toString());
if (Guessas == number) {
Tekstas.setText("Congratulations! You got it right!");
} else if (Guessas > number) {
Tekstas.setText("Your number is too high, try again!");
} else if (Guessas < number) {
Tekstas.setText("Your number is too low, try again!");
}
}
}
我希望TextView说:“恭喜!你做对了!”,当Guessas等于数字时,“你的数字太高,再试一次!”,当Guessas高于数字并且“你的数字也是低,再试一次!“,当Guessas低于数字时。
当我按下触发此代码块的按钮时,当EditText中有数字时,程序崩溃。
答案 0 :(得分:0)
从
更改代码int Guessas = Integer.parseInt(Spejimas.toString());
到
int Guessas = Integer.parseInt(Spejimas.getText().toString());
除了仅包含数字的字符串值外,问题是Integer.parseInt()
。在这里,您尝试将edittext
作为字符串发送。将编辑文本转换为包含数字以外字符的字符串时。
答案 1 :(得分:0)
那是因为你没有投射getText方法返回的值。 getText返回Editable。您应该将toString()方法添加到您调用getText的所有位置,如下所示:
if (Spejimas.getText().toString().length() == 0) {
Tekstas.setText("Oops, you forgot to type your guess!");
} else if (Spejimas.getText().toString().length() != 0) {
int Guessas = Integer.parseInt(Spejimas.getText().toString());
if (Guessas == number) {
Tekstas.setText("Congratulations! You got it right!");
} else if (Guessas > number) {
Tekstas.setText("Your number is too high, try again!");
} else if (Guessas < number) {
Tekstas.setText("Your number is too low, try again!");
}
}
而且,你在这一行中遇到了一个问题:
int Guessas = Integer.parseInt(Spejimas.toString());
您应该将其更改为:
int Guessas = Integer.parseInt(Spejimas.getText().toString());