我正在研究一个计算器应用程序,我正在尝试从两个不同的TextView中获取两个字符串值并将它们转换为双精度数,因此我可以对它们进行操作。问题是,当我尝试将字符串转换为双精度数时,它不起作用,并且会使应用程序崩溃。我在try catch块中尝试过它,每次都有一个NumberFormatException。以下是无法正常工作的行:
readRecords
以下是完整代码:
double doubleContents1 = Double.parseDouble(stringContents1);
// convert first value from string to double
double doubleContents2 = Double.parseDouble(stringContents2);
// convert second value from string to double
logcat:
public void sendMessageEquals(View view) {
TextView textView2 = (TextView) findViewById(R.id.textView2);
// this is the first textview, for the first number
TextView textView3 = (TextView) findViewById(R.id.textView3);
// second textview for the second number
TextView textView4 = (TextView) findViewById(R.id.textView4);
// third textview for displaying the result from the first two
String stringContents1 = (String) textView2.getText();
// get the value from the first textview
String stringContents2 = (String) textView3.getText();
// get the value from the second textview
double doubleContents1 = Double.parseDouble(stringContents1);
// convert first value from string to double
double doubleContents2 = Double.parseDouble(stringContents2);
// convert second value from string to double
if (operator.equals("+")) {
Double doubleContents3 = doubleContents1 + doubleContents2;
String stringContents3 = Double.toString(doubleContents3);
textView4.setText(stringContents3);
state = "Phase1";
}
else if (operator.equals("-")) {
Double doubleContents3 = doubleContents1 - doubleContents2;
String stringContents3 = Double.toString(doubleContents3);
}
else if (operator.equals("*")) {
Double doubleContents3 = doubleContents1 * doubleContents2;
String stringContents3 = Double.toString(doubleContents3);
}
else if (operator.equals("/")) {
if (doubleContents2 != 0) {
Double doubleContents3 = doubleContents1 / doubleContents2;
String stringContents3 = Double.toString(doubleContents3);
}
}
else {
state = "Phase1";
}
}
答案 0 :(得分:2)
logcat异常表示您的字符串是“操作数1:”,因此无法将其解析为 [Tag 1]=>"Tag 1",
[Tag 2]=>"Tag 2"
。
您应该从Double
而不是EditText
中获取值。
答案 1 :(得分:0)
我的申请中有一个类似的例子。这对我有用:
double doubleContents1 = Double.parseDouble(textView2.getText().toString());
double doubleContents2 = Double.parseDouble(textView2.getText().toString());
如果这个剂量有帮助,请通过编辑您的问题发布您的logcat,以便我们查看此错误