1

我遇到的问题是,当我根本没有输入任何数据,或者如果其中一个输入框中只有数据时程序崩溃,但是如果两个框中都有任何数据,程序工作正常,那么我该如何阻止它如果没有输入,则发送数据。错误说它可以解析双值“”

    calculate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            distanceTraveled = Double.parseDouble(distance.getText().toString());
            fuelUsed = Double.parseDouble(fuel.getText().toString());
            part1 = fuelUsed / 4.55;
            mpg = distanceTraveled / part1;
            total.setText(String.format("%.2f", mpg));
        }
    });
4

2 回答 2

1

在进行计算之前将 EditView 更改为空或 null:

alculate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
          if(distance.getText().toString().length() > 0){

            distanceTraveled = Double.parseDouble(distance.getText().toString());
        }
        else{
              distanceTraveled=0; // put default value here
          }
        if(fuel.getText().toString().length() > 0){  
               fuelUsed = Double.parseDouble(fuel.getText().toString());
          }
          else{
               fuelUsed=0;// put default value here

           }
            part1 = fuelUsed / 4.55;
            mpg = distanceTraveled / part1;
            total.setText(String.format("%.2f", mpg));
        }
    });
于 2012-12-02T17:12:21.697 回答
0

在尝试从输入字段中检索值之前,请检查它们是否为空:

if (distance.getText() != null && fuel.getText() != null ) {
    distanceTraveled = Double.parseDouble(distance.getText().toString());
    fuelUsed = Double.parseDouble(fuel.getText().toString());
    part1 = fuelUsed / 4.55;
    mpg = distanceTraveled / part1;
    total.setText(String.format("%.2f", mpg));
} else {
    // You can display a message here for example Toast message that fields cannnot be empty
{
于 2012-12-02T17:12:02.457 回答