-1
public class simpleClass{
    public static void main(String[] args){
        String a = "2 + 3";
        double b = Double.parseDouble(a);
        System.out.println(b);
    }
}

That's just simple code to show what's my problem.

Why this won't work when I run the program?

I'm making a simple calculator in Spring and I'm adding numbers as a String (also +, -, /, *) but after parsing I'm getting errors in IJ.

Daker
  • 1

3 Answers3

2

You can use ScriptEngine to evaluate a string and parse it to a double.

Like this:

public static void main(String[] args) {
    // Base Query
    String a = "5 * 2";

    // Query Result
    double b = EvalMath(a);

    // Print Result
    System.out.println(b);
}

// Evalute Math in String
static double EvalMath(String a) {
    double result = 0;

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    try {
        result = Double.parseDouble(engine.eval(a).toString());
    } catch (ScriptException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result;
}

Hope it helps! :D

0

Double.parseDouble() can't translate characters that are doubles into doubles, so ' + ' will break that line.

Try:

string a1 = "2";
string a2 = "3";
double b = Double.parseDouble(a1) + Double.parseDouble(a2);
System.out.println(b);
MyStackRunnethOver
  • 4,872
  • 2
  • 28
  • 42
danbutts
  • 94
  • 1
  • 8
0

Check it First: Double.parseDouble() which takes string. If it's not a number it'll throw an NumberFormatException. 2 + 3 is a expression. So this method can't parse it to double.

Full Solution here:

public class simpleClass {
public static void main(String[] args) {
    String a = "2 + 3";
    /// First of all don't add space on equation
    a.replaceAll(" ", ""); // This will remove all whitespace
    double op1 = 0, op2 = 0; // variable for storing value
    char operand = '\0'; // operand
    boolean flag = false; // false means no value taken for operation

    for (int i = 0; i < a.length(); i++) {
        String tmp = "";
        if (Character.isDigit(a.charAt(i))) {
            tmp += a.charAt(i);
            if (!flag)
                op1 = Double.parseDouble(tmp);
            else
                op2 = Double.parseDouble(tmp);
        } else if (a.charAt(i) == '+' || a.charAt(i) == '-' || a.charAt(i) == '*' || a.charAt(i) == '/') {
            operand = a.charAt(i);
            flag = true; // now we have a value in op1
        }
    }
    double result = 0;

    if (operand == '+') {
        result = op1 + op2;
    } else if (operand == '-') {
        result = op1 - op2;
    } else if (operand == '*') {
        result = op1 * op2;
    } else if (operand == '/') {
        result = op1 / op2;
    }

    System.out.println(result);
}

}

Output: 5