gpt4 book ai didi

java - 在android中使用异常

转载 作者:行者123 更新时间:2023-12-01 05:40:35 26 4
gpt4 key购买 nike

尊重所有人;

我是编程新手,发现了一个障碍,即在编辑文本框中没有输入任何内容的情况下单击按钮会使我的 Activity 崩溃。

经过研究,我得到了 Try and 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();
}}

但主要问题是我必须在所有按钮方法中使用它。还有其他方法可以避免代码中的这种重复吗?

请帮忙..

最佳答案

像这样修改代码。希望对您有帮助。

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();
}}

关于java - 在android中使用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7291744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com