我正在尝试创建一个应用来计算线段的距离,但是当距离应为0时,应用会崩溃。我假设它与尝试平方根或平方根0有关,但我可能是错的。问题是什么,我该如何解决?
我的代码:
package com.jenglanddev.quikformcalclite;
import java.math.BigDecimal;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Distance extends Activity implements OnClickListener {
EditText x1, y1, x2, y2;
Button calc;
TextView dist1, dist2;
String X1, Y1, X2, Y2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.distance);
x1 = (EditText) findViewById(R.id.distance_x1);
y1 = (EditText) findViewById(R.id.distance_y1);
x2 = (EditText) findViewById(R.id.distance_x2);
y2 = (EditText) findViewById(R.id.distance_y2);
calc = (Button) findViewById(R.id.distance_calc);
dist1 = (TextView) findViewById(R.id.distance_distance1);
dist2 = (TextView) findViewById(R.id.distance_distance2);
calc.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
BigDecimal f;
X1 = x1.getText().toString();
if (X1.contentEquals("")) {
X1 = "0";
}
Y1 = y1.getText().toString();
if (Y1.contentEquals("")) {
Y1 = "0";
}
X2 = x2.getText().toString();
if (X2.contentEquals("")) {
X2 = "0";
}
Y2 = y2.getText().toString();
if (Y2.contentEquals("")) {
Y2 = "0";
}
BigDecimal x1 = new BigDecimal(X1);
BigDecimal y1 = new BigDecimal(Y1);
BigDecimal x2 = new BigDecimal(X2);
BigDecimal y2 = new BigDecimal(Y2);
BigDecimal a = x2.subtract(x1);
BigDecimal b = y2.subtract(y1);
BigDecimal c = a.multiply(a);
BigDecimal d = b.multiply(b);
BigDecimal e = c.add(d);
f = sqrt(e);
dist1.setText("Distance = The Square Root Of " + e + " Units");
dist2.setText("Distance = " + f + " Units");
}
public static BigDecimal sqrt(BigDecimal value) {
BigDecimal x = new BigDecimal(Math.sqrt(value.doubleValue()));
return x.add(new BigDecimal(value.subtract(x.multiply(x)).doubleValue()
/ (x.doubleValue() * 2.0)));
}
}
当距离为任何其他数字时,此工作正常,而不是0。
答案 0 :(得分:5)
问题不在于sqrt,而在于你除以零。
当值为零时,则x将为零,并且除以x * 2.0。
只需添加一个检查,以便在值为零时返回零。
if(value.compareTo(BigDecimal.ZERO) == 0)
return BigDecimal.ZERO;