尊重所有人;
我是编程新手并找到一个障碍,即单击按钮时没有在Edittext框中输入任何内容会将我的活动转换为崩溃。
所以经过研究后我得到了Try和catch方法,并且效果很好。
public void clickDiv(View button){
try{
EditText Input = (EditText) findViewById(R.id.editext);
String input = Input.getText().toString();
String empty = "";
Float floatInput = new Float (input);
TextView TextShow = (TextView) findViewById(R.id.textView1);
String Newinput = floatInput.toString();
TextShow.setText(Newinput);
if (answer == 0){
answer = (answer+1) / floatInput ;
}else{
answer = (answer) / floatInput ;
}
String answerString = answer.toString();
TextShow.setText(answerString);
Input.setText(empty); }
catch (Exception e) {
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setMessage("Could not find the operand");
alertDialog.show();
}}
但主要问题是我必须在所有按钮方法中使用它。 是否还有其他方法可以避免代码中出现这种重复。
请帮助..
答案 0 :(得分:0)
像这样修改代码。希望它可以帮到你。
public void clickDiv(View button){
try{
EditText Input = (EditText) findViewById(R.id.editext);
String input = Input.getText().toString();
//if no input, set the error to the edittext and return
if(input.trim().length()==0){
Input.setError("An input is required");
return;
}
String empty = "";
Float floatInput = new Float (input);
TextView TextShow = (TextView) findViewById(R.id.textView1);
String Newinput = floatInput.toString();
TextShow.setText(Newinput);
if (answer == 0){
answer = (answer+1) / floatInput ;
}else{
answer = (answer) / floatInput ;
}
String answerString = answer.toString();
TextShow.setText(answerString);
Input.setText(empty); }
catch (Exception e) {
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setMessage("Could not find the operand");
alertDialog.show();
}}