0

有没有办法为字符串预定义一个值,以便在任何字段为空时不出现错误?所有的 porcentagem 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!"); }
        }
    });
}

谢谢

4

2 回答 2

2

每次提交表单时,您应该检查每个字段是否具有正确的值。例如,如果您想检查天气,可选字段是否有值,您应该执行以下操作:

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
} 
于 2013-02-24T00:35:09.803 回答
1

使用该属性将值添加到您的 xml 布局中,android:text="..."或者用于TextUtils.isEmpty(...)检测字符串是否为空并自己分配默认值。

于 2013-02-24T00:32:08.160 回答