gpt4 book ai didi

java - 空字段导致错误 "stopped unexpectedly"

转载 作者:行者123 更新时间:2023-12-01 23:59:56 26 4
gpt4 key购买 nike

是否有任何方法可以预定义字符串值,以便在任何字段为空时不会出现错误?所有比例1、2和3都是可选的,因此并不是要求用户输入一些数据,而是预先定义值以便不具有这些值。初学者问题。

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

cpc_inicial = (EditText) findViewById(R.id.cpc_inicial);
porcentagem1 = (EditText) findViewById(R.id.porcentagem1);
porcentagem2 = (EditText) findViewById(R.id.porcentagem2);
porcentagem3 = (EditText) findViewById(R.id.porcentagem3);
cpc_final = (TextView) findViewById(R.id.cpc_final);
botao1 = (Button) findViewById(R.id.botao1);

cpc_inicial.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem1.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem2.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem3.setInputType(InputType.TYPE_CLASS_NUMBER);

botao1.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

if(porcentagem3 != null ) {

float cpc = Float.parseFloat(cpc_inicial.getText().toString());
float v1 = Float.parseFloat(porcentagem1.getText().toString());
float v2 = Float.parseFloat(porcentagem2.getText().toString());
float v3 = Float.parseFloat(porcentagem3.getText().toString());
TextView cpcfinal = cpc_final;

if(cpc > 0.0 && v1 != 0.0 && v2 != 0.0 && v3 != 0.0 )
{
soma = (cpc*v1/100)+cpc;
soma = soma*(v2/100)+soma;
soma = soma*(v3/100)+soma;

String sum = Float.toString(soma);
cpcfinal.setText(sum);

}
} else
{
TextView cpcfinal = cpc_final;
soma = 0;
cpcfinal.setText("ops!"); }
}
});
}

谢谢

最佳答案

每次提交表单时,您都应该检查每个字段是否有正确的值。例如,如果您想检查可选字段是否有值,您应该这样做:

String optionalText = optionalFieldName.getText().toString();
if (optionalText.equals("some expected value")) {
//Do something with the value here.
}

当然,您需要对每个可选字段执行类似的操作,并且实际上还应该对不是安全选项的字段执行相反的操作,并且可能警告用户该字段是必需的,例如:

String text = fieldName.getText().toString();
if (text.equals("")) {
//field is empty, so warn the user that it is required.
}

如果您正在寻找的值本质上应该是数字,那么您应该这样做:

String text = field.getText().toString();
if (!text.equals("")) {
//Field has at least some text in it.
try {
float val = Float.parseFloat(text);
}catch (NumberFormatException ex) {
//Enterered text was not a float value, so you should do something
// here to let the user know that their input was invalid and what you expect
}

//Do something with the value
}

关于java - 空字段导致错误 "stopped unexpectedly",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15047354/

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