gpt4 book ai didi

java - 当文本编辑留空时应用程序强制关闭

转载 作者:行者123 更新时间:2023-12-01 13:32:18 26 4
gpt4 key购买 nike

我是一名新的 Android 程序员,我正在尝试制作一个“二次方程求解器应用程序”。用户必须在 3 个各自的 TextEdit-s 中输入 3 个值,并且这些值以 double 形式存储。如果用户将其中一项输入留空,应用程序将强制关闭。如何默认将所有值设置为 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("");
}

}

});

最佳答案

这是 Double.parseDouble(..) 行的 NPE。

创建此函数

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());

关于java - 当文本编辑留空时应用程序强制关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21497201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com