字符串加倍

时间:2012-08-26 08:46:40

标签: java android

我尝试从屏幕上读取文本并将其更改为double并且崩溃

public void equesionOperation(int signNum1) {

        S_numInTV=TV_calcScreen.getText().toString();
        S_numUp=TV_calcUp.getText().toString();

        D_numIn=Double.parseDouble(S_numInTV);
        D_numToCalc=Double.parseDouble(S_numUp);

        switch (signNum1){
        case 1: D_sum=D_numIn+D_numToCalc;break;
        case 2: D_sum=D_numIn-D_numToCalc;break;
        case 3: D_sum=D_numIn*D_numToCalc;break;
        case 4: D_sum=D_numToCalc/D_numIn;break;
        case 5: D_sum=Math.pow(D_numToCalc, D_numIn);break;
        default: break;
        }
        S_sum=(""+D_numToCalc+"  "+D_numIn);
    }

2 个答案:

答案 0 :(得分:0)

这可能有助于找到崩溃的原因。用以下代码替换第3和第4代码:

try {
   D_numIn=Double.parseDouble(S_numInTV);
} catch (NumberFormatException nfe) {
   System.out.printf("Attempted to parse a double, but found: '%s'%n", S_numInTV);
}
try {
D_numToCalc=Double.parseDouble(S_numUp);
} catch (NumberFormatException nfe) {
   System.out.printf("Attempted to parse a double, but found: '%s'%n", S_numUp);
}

答案 1 :(得分:0)

 S_numInTV=TV_calcScreen.getText().toString();
 S_numUp=TV_calcUp.getText().toString();

这些字符串值是文字还是数字?

String str1 = "100.476";
Double dObj2 = Double.valueOf(str1);
System.out.println(dObj2);

以上代码不会发生任何异常,但

String str1 = "ss";
    Double dObj2 = Double.valueOf(str1);
    System.out.println(dObj2);

上面的代码会出现numberfomatexception

因此,在将字符串转换为double之前,您必须确保输入哪个字符串;