我正在尝试制作一个接受输入并自动将其更改为 int 的应用程序。但是,当它尝试获取 int 时,应用程序会自动停止。以下是完整代码...
public class MainActivity extends Activity implements OnClickListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button calculate = (Button)findViewById(R.id.calculateTip);
calculate.setOnClickListener(this);
}//end onCreate
public void onClick(View v) {
EditText money = (EditText)findViewById(R.id.bill);
int bill = Integer.parseInt(money.getText().toString());
money.setText("Event Processed");
}//end onClick
}//end MainActivity
最佳答案
我怀疑应用程序正在停止,因为您尝试解析的值实际上并不是整数。您应该将该代码放入 try catch 中。
即:
public void onClick(View v) {
EditText money;
try
{
money = (EditText)findViewById(R.id.bill);
// This check makes sure that the EditText is returning the correct object.
if(money != null)
{
int bill = Integer.parseInt(money.getText().toString());
money.setText("Event Processed");
}
}
catch(NumberFormatException e)
{
// If we get in here that means the inserted value was not an Integer. So do something.
//ie:
money.setText("Please enter a value amount" );
}
}//end onClick
无论如何,您应该将此代码放在 try catch 中以保持数据完整性。
希望这有帮助! 干杯。
关于java - 当我尝试获取 Int 时我的应用程序停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12682688/