Search code examples
androidnumberformatexception

NumberFormatException when typecasting from String Array to Double


i am trying to convert a string to a double. I was able to do it in many situations but this time, it is giving me a NumberFormatException. Here is the code...

//strExpression = 2^3 (My Input in the editText)

strExpression = edtxtExpression.getText().toString();

try
{
   System.out.println("Inside Power case");
   //expSplit is a String[]
   expSplit = strExpression.split("^");
   double first = Double.parseDouble(expSplit[0]);
   System.out.println("First Number "+first);
   double second = Double.parseDouble(expSplit[1]);
   System.out.println("Second Number "+second);

   double result = Math.pow(first, second);
   System.out.println("Result "+result);
   edtxtExpression.setText(first+" ^ "+second+" = "+result);

}
catch (Exception e) {
    // TODO: handle exception
    Toast.makeText(this, e.getClass().toString(), 100).show();

}

Exception:::

01-01 03:07:45.169: I/System.out(11287): Inside Power case
01-01 03:07:45.179: I/System.out(11287): class java.lang.NumberFormatException

I get the "Inside Power" output but the other print statements doesn't get executed. where am i going wrong?


Solution

  • ^ is a reserved character in RegEx, try \\^.

    expSplit = strExpression.split("\\^");