1

basically, i need to input an equation with an 'x' value (ex. 3x + 5). then the next input would be the value of x. all the x in the equation will then be replaced by the given value. what i did was to input the equation as string and then used string.replace to replace x with the given value.

    System.out.print("enter equation: ");
    Scanner sc = new Scanner(System.in);
    String equation = sc.nextLine();
    System.out.print("value of x: ");
    int x=sc.nextInt();
    String xx= Integer.toString(x);
    equation= equation.replace("x",xx);
    System.out.println(equation);

problem is, since the string equation may have "+" or "-", i can't convert the string to int. any suggestions what to convert the string into such that it can be solvable? also if the x is next to a number (ex. 4x) is there a way that it can be multiplied?

cacuts
  • 11
  • 1
  • 1
    There's always something like this http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form but be careful of untrusted inputs. – Iluvatar Dec 06 '16 at 10:37
  • Did you search on SO ? There is already some question like this give some interesting solution – AxelH Dec 06 '16 at 10:37
  • have a look at https://en.wikipedia.org/wiki/Interpreter_pattern – user902383 Dec 06 '16 at 10:38

0 Answers0