字符串为空时如何停止应用程序崩溃

K.M*_*Mir 0 java crash android

没有文本时,应用程序崩溃!我没有什么可以解决的!谢谢

enter  TextView TotalTextView;
EditText EnterPercentage;
EditText EnterPrice;

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


    TotalTextView = (TextView) findViewById(R.id.TotalTextView);
    EnterPercentage = (EditText) findViewById(R.id.EnterPercentage);
    EnterPrice = (EditText) findViewById(R.id.EnterPrice);
    Button CalcBtn = (Button) findViewById(R.id.CalcBtn);


    CalcBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                float percentage = Float.parseFloat(EnterPercentage.getText().toString());
                float prix = Float.parseFloat(EnterPrice.getText().toString());
                float dec = percentage / 100;
                float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());

                TotalTextView.setText(String.format("%.2f", total));


        }
    });
Run Code Online (Sandbox Code Playgroud)

感谢您的回答,我是初学者,所以...谢谢!

if (EnterPercentage.getText().equals("")) {

                float percentage = Float.parseFloat(EnterPercentage.getText().toString());
                float prix = Float.parseFloat(EnterPrice.getText().toString());
                float dec = percentage / 100;
                float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
                TotalTextView.setText(String.format("%.2f", total));


            } else {
Run Code Online (Sandbox Code Playgroud)

}

该按钮不执行任何操作,但应用程序不会崩溃

小智 5

我们检查String的长度...当它为0时,我们什么也不做。当String> 0时,您的代码正在运行。

喜欢:

            if (EnterPercentage.getText().trim().toString().length() == 0 || EnterPrice.getText().toString().length() == 0 ) {
                //Textfields are empty.
                Log.d("Error","Fields are empty");
            } else {
                //Textfield is full
                float percentage = Float.parseFloat(EnterPercentage.getText().toString());
                float prix = Float.parseFloat(EnterPrice.getText().toString());
                float dec = percentage / 100;
                float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
                TotalTextView.setText(String.format("%.2f", total));
            }
Run Code Online (Sandbox Code Playgroud)