3 回答
TA贡献1895条经验 获得超7个赞
正如您在问题中提到的那样,当您未在编辑文本中输入任何内容时会发生此错误。
所以首先,检查是否edit text为空,然后执行所需的操作
btnGuess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!etNumber.getText.toString().equals("")) {
int guessValue = Integer.parseInt(etNumber.getText().toString());
String message;
if(guessValue > randomNumber){
message = "Lower !";
etNumber.setText("");
}
else if (guessValue < randomNumber){
message = "Higher !";
etNumber.setText("");
}
else{
message = "You got it right. GG ";
etNumber.setText("");
generateRandomNos();
}
Toast.makeText(MainActivity.this,message,Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this,"EditText Is empty",Toast.LENGTH_SHORT).show();
}
});
注意:并确保您使用android:inputType="number"属性来编辑文本,以便您只能获得数字作为输入
TA贡献1757条经验 获得超8个赞
您是否在 EditText 中输入了除十进制数字以外的任何其他字符?
parseInt文档说:
Parses the string argument as a signed decimal integer.
The characters in the string must all be decimal digits,
except that the first character may be an ASCII minus sign '-' ('\u002D') to
indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a
positive value. The resulting integer value is returned, exactly as if the
argument and the radix 10 were given as arguments to the
parseInt(java.lang.String, int) method.
您可以使用 try/catch 语法来检查这个
try {
int value = Integer.parseInt(str);
} catch(NumberFormatException ex) {
//Input is not a number
}
TA贡献1818条经验 获得超7个赞
当然它会崩溃,因为您从未generateRandomNos()在 Click 事件之前分配此方法。所以你的应用程序不知道randomNumber事件触发前的值是多少。您现在可以做的是在执行 btnGuess clicked 之前获取值randomNumber。例如
btnGuess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
generateRandomNos(); // i change this position
int guessValue =
Integer.parseInt(etNumber.getText().toString());
String message;
if(guessValue > randomNumber){
message = "Lower !";
etNumber.setText("");
}
else if (guessValue < randomNumber){
message = "Higher !";
etNumber.setText("");
}
else{
message = "You got it right. GG ";
etNumber.setText("");
}
添加回答
举报