Home > database >  Converting string with symbols to Integer or double type
Converting string with symbols to Integer or double type

Time:11-27

Image of code

With this i am not able to convert a string which cointains symbols like ( , - , / , *) to double or integer .

I am expecting to get the answer as integer and all with all solving inputed in the string.

Your every effort is greatly appreciated , Thank you

CodePudding user response:

You can do that by loop through each characters and check if it's the operator or not and use substring

Here is an example

public class Main {
    public static void main(String[] args) {
        String a = "112   221";
        double y = computeString(a);
        System.out.println(y);
    }

    public static double computeString(String a) {
        double y = 0;
        for (int i = 0; i < a.length(); i  ) {
            // if the character is an operator
            if (a.charAt(i) == ' ') {
                // get the first number before the operator and convert it to a double value
                // then assign it to the total value y
                // then get the second number after the operator and convert it to a double value
                // then add it to the total value y
                y =  Double.parseDouble(a.substring(0, i))   Double.parseDouble(a.substring(i   2, a.length()));
                // first substring(0, i) gets the first number before the operator
                // second substring(i   2) gets the second number after the operator
            }
        }
        return y;
    }
}

If you want to make it valid to symbol like '-', ' ', '*', '/' change the operator in if statement in the function or add another condition and apply the same logic as I demonstrate in the function :)

CodePudding user response:

You can use the rhino class and evaluate it as a Javascript string.

implementation Lib in Gradle by adding

implementation 'io.apisense:rhino-android:1.1.1' 

then you can use it by

Object result = null;

ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");

if (engine == null) {
    throw new UnsupportedOperationException("JavaScript scripting engine not found");
}
try {
    result = engine.eval("5 5"); // <- you can use mathematics operations
} catch (Exception  e) {
    Log.i("e",e.toString());
}
Log.i("ResultData" , result.toString());  // will be print (10)
double val =  Double.parseDouble(result.toString());
  • Related