-3

I am trying to write a java program (which is part of an assignment) which allows users to input their own function, and then the program calculates it and gets a value. I have actually written a program that calculates an IVP (Initial Value Problem) using the Euler-Cauchy method. My initial function was -2*t*u^2. However, what if I want to work on 4*t*u^3 instead or some other formula?

I tried getting the formula as String from the user, but I am having difficulty in matching a particular variable (e.g. t or u) to a number.

hsirkar
  • 769
  • 1
  • 8
  • 19
  • Why are you "having difficulty in matching a particular variable"? Could you be a little more specific? Can you post the code? – hsirkar Jul 26 '15 at 20:46
  • is this formula has the same form every time or it can be any formula user type? – nkcode Jul 26 '15 at 20:47
  • /* *Let me use this to see if i can clarify */ //Taking for example a formula input which is the product of u and t String input = "u * t"; // Assume i got the value of u & t through scanner or some other io int u=5, t= 3; // how can i make my program know that u=5 should be multiplied by t=3 based on the user formula System.out.println(input); – James Anyanwu Jul 26 '15 at 21:54
  • You can use String's replace function if that is what you're looking for. For example, to replace the u in the string "u * t", you can do String.replace("u", u). The "u" is the "u" in the string and the u (with no quotes) is the integer variable. – hsirkar Jul 26 '15 at 21:56
  • This might help at some point: [Evaluating a math expression given in string form](http://stackoverflow.com/q/3422673) – Tom Jul 26 '15 at 22:10

1 Answers1

0

Use the String.replace() function to convert the u and t from the formula string to the actual variables, then take a good look at this Stack Overflow question: Convert String to Code

Community
  • 1
  • 1
hsirkar
  • 769
  • 1
  • 8
  • 19