[英]App force closes when a textedit is left blank
我是一名新的android程序员,我正在尝试制作“ Quadratic Equation Solver App”。 用户必须在3个相应的TextEdit中输入3个值,并且这些值以双精度形式存储。 如果用户将输入之一留空,则应用程序强制关闭。 如何将所有值默认设置为0,这样应用程序不会强制关闭?
public class MainActivity extends Activity {
EditText inputA, inputB, inputC;
TextView nrRoots, root1, root2, roots;
Button bStepByStep, calculate;
Double a, b, c, D, x1, x2, x, dRootNr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputA = (EditText) findViewById(R.id.etParamA);
inputB = (EditText) findViewById(R.id.etParamB);
inputC = (EditText) findViewById(R.id.etParamC);
nrRoots = (TextView) findViewById(R.id.tvNrRoots);
root1 = (TextView) findViewById(R.id.tvRoot1);
roots = (TextView) findViewById(R.id.tvRoots);
root2 = (TextView) findViewById(R.id.tvRoot2);
calculate = (Button) findViewById(R.id.bCalculate);
bStepByStep = (Button) findViewById(R.id.bStepByStep);
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
a = Double.parseDouble(inputA.getText().toString());
b = Double.parseDouble(inputB.getText().toString());
c = Double.parseDouble(inputC.getText().toString());
double D = Math.sqrt((b * b) - (4 * a * c));
if (D == 0) {
nrRoots.setText("The equation " + a + "x^2+" + b + "x+" + c
+ "=0 has 1 distinct root.");
x = ((-1) * b) / (2 * a);
root1.setText("x=" + x);
root2.setText("");
roots.setText("");
} else if (D > 0) {
nrRoots.setText("The equation " + a + "x^2+" + b + "x+" + c
+ "=0 has 2 distinct roots.");
x1 = (((-1) * b) + D) / (2 * a);
x2 = (((-1) * b) - D) / (2 * a);
root1.setText("x1= " + x1);
root2.setText("x2= " + x2);
} else {
nrRoots.setText("The equation " + a + "x^2+" + b + "x+" + c
+ "=0 has no distinct roots.");
root1.setText("");
root2.setText("");
}
}
});
这是NPE,位于Double.parseDouble(..)
。
创建此功能
public double getDouble(String str) {
if (str != null) {
if (str.equalsIgnoreCase("")) {
return 0;
} else {
return Double.parseDouble(str);
}
} else {
return 0;
}
}
然后使用此代码
a = getDouble(inputA.getText().toString());
b = getDouble(inputB.getText().toString());
c = getDouble(inputC.getText().toString());
在xml文件中
android:text="0"
android:inputType="numeric"
将“ 0”设置为默认值,并设置数字输入类型,以确保不会输入任何非数字。
并且
在分析之前进行控制,以防用户可能会清除edittext。
if (!input.getText().toString().equals("")){
//parse
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.