请大家好我正在编写这个Android应用程序,但我在logCat中遇到运行时错误:java.lang.RuntimeException:无法启动活动:java.lang.NumberFormatException:无效的int:&#34 ;"
public class MainActivity extends Activity{
EditText et;
Button guess, randomize;
TextView tv1, tv2;
int num1;
int num2;
int userAns;
int answer;
final Random rand = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et = (EditText) findViewById(R.id.editText1);
tv1 = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
guess = (Button) findViewById(R.id.btnSubmit);
randomize = (Button) findViewById(R.id.button1);
randomize(rand);
tv2.setText(num1 + " + " + num2);
userAns = Integer.parseInt(et.getText().toString());
guess.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
answer = num1 + num2;
if (userAns == answer) {
tv1.setText("Correct... The Answer is " +answer);
} else {
tv1.setText("wrong");
}
}
});
randomize.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
randomize(rand);
}
});
}
private void randomize(final Random rand) {
num1 = 1 + rand.nextInt(50);
num2 = 1 + rand.nextInt(50);
}
}
答案 0 :(得分:1)
numberFormatException通常是由字符串到int转换错误引起的。我怀疑这条线。
userAns = Integer.parseInt(et.getText().toString());
因为它还没有用文本初始化。
将其包装在try / catch
中修改强>: 如何修复
我建议搬家
userAns = Integer.parseInt(et.getText().toString());
在guess.setOnClickListener里面如此:
guess.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
answer = num1 + num2;
try {
userAns = Integer.parseInt(et.getText().toString());
if (userAns == answer) {
tv1.setText("Correct... The Answer is " +answer);
} else {
tv1.setText("wrong");
}
} catch(Exception e) {
// output error that 'et' field is emtpy or doesnt contain a number
}
}
});
答案 1 :(得分:0)
为空。因此,et.getText将返回"",这不是有效数字,因此parseInt将抛出异常。您需要等待获取该文本,直到用户按下猜测按钮然后获取它。