将字符串解析为int时出错

时间:2022-10-17 09:05:41

Im generating 2 random values and in EditText you need to enter a result of adding this 2 values and when im tring to parse that what i get from edittext it crash my application

我生成2个随机值,在EditText中你需要输入添加这2个值的结果,当我想要解析我从edittext获得的内容时它会使我的应用程序崩溃

public class Main2Activity extends AppCompatActivity {

public int wynik;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    setContentView(R.layout.activity_main2);
    TextView text = (TextView) findViewById(R.id.txtv);

    Random r = new Random();
    int i1 = (r.nextInt(100 - 1) + 1);
    int i2 = (r.nextInt(100 - 1) + 1);
    text.setText(i1 +" + " + i2 + " = ");
    wynik =i1+i2;
};
    public void backtomain(View view)
    {
        EditText editText = (EditText) findViewById(R.id.edittext);
        String etstring =editText.getText().toString();
        Integer etint = Integer.parseInt(etstring); <---------------- CRASH CUZ OF THIS LINE

        //if(etint==wynik)
        //{
            Intent intent = new Intent(this, AalarmActivity.class);
            intent.putExtra("toggleBtn", true);
            startActivity(intent);
            finish();
        //}
        //else
        //{
        //    Toast.makeText(this, "Error ",
        //            Toast.LENGTH_LONG).show();
        //}
    }
}

Commented lines are not finished first need to repair that parsing part.

注释行未完成首先需要修复该解析部分。

1 个解决方案

#1


3  

You probably is receiving a input that is not a number.

您可能正在接收不是数字的输入。

You can force to use the input type as mumber, modify your EditText in XML and include this property:

您可以强制将输入类型用作mumber,在XML中修改EditText并包含以下属性:

android:inputType="number" 

This will force to user input only numbers, and your Integer.parseInt(etstring); should parse the number without format exceptions.

这将强制用户只输入数字和你的Integer.parseInt(etstring);应该在没有格式异常的情况下解析数字。

#1


3  

You probably is receiving a input that is not a number.

您可能正在接收不是数字的输入。

You can force to use the input type as mumber, modify your EditText in XML and include this property:

您可以强制将输入类型用作mumber,在XML中修改EditText并包含以下属性:

android:inputType="number" 

This will force to user input only numbers, and your Integer.parseInt(etstring); should parse the number without format exceptions.

这将强制用户只输入数字和你的Integer.parseInt(etstring);应该在没有格式异常的情况下解析数字。