0

For my algebra project I am making a java program that can graph an equation you type in. I got free basic graphing code from a website, and implemented a couple things. In the code, when it returns the equation for the graph, it is a double. In the code, you can change the equation in the double and it will graph it fine. When I try to put my string in the code(from user input) the program will crash if i put anything like X or * or / in the equation. I tried to put (Double.parseDouble(equation)) in the double, but it still doesn't work. BTW i am new at java. Thanks!

This is what the code looks like(class "circle1"):

public double getY(double x) { return (Double.parseDouble(equation)); }

In the class that reads the equation, here is the code:

graph.functions.add(new Circle1());

(equation is the string)

  • 2
    `Double.parseDouble()` does exactly what it says it does. It doesn't parse X, *, or /. – awksp May 02 '14 at 03:54
  • Also, what do you mean by "the equation is a double"? Can you provide an example of an equation that works and an equation that doesn't? – awksp May 02 '14 at 03:54
  • possible duplicate of [Evaluating a math expression given in string form](http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) – Sergey Kalinichenko May 02 '14 at 03:55
  • If i do this: public double getY(double x) { return (5*x*x-3*x+7); } The graph will work, if i type that in as the string "equation", this will not work: public double getY(double x) { return (Double.parseDouble(equation)); } – user3594921 May 02 '14 at 13:24

2 Answers2

0

Double.parseDouble() can only parse double values. For example if your string value is "5" , "5.0" or "5.89", Double.parseDouble() won't throw an exception.

If you want to parse an equation, you will have to parse it using your own logic. For example you will have to search for operators (like +,-,/) , split the string on them and then process the input.

Adam Batkin
  • 51,711
  • 9
  • 123
  • 115
Biswajit_86
  • 3,661
  • 2
  • 22
  • 36
  • Thanks! I have one quick question(im newb) how would you search for the operators? – user3594921 May 02 '14 at 13:27
  • You would have to use regular expression to see if there are any operators.G through the documentation of the contains, indexof and matches method and you will understand what needs to be done – Biswajit_86 May 02 '14 at 15:10
0

If you are allowed to use libraries http://code.google.com/p/symja/wiki/MathExpressionParser may be what you are looking for

Totò
  • 1,824
  • 15
  • 20