given a file with input:
Formula: m = (y - c) / x
Formula: m = y + c^2
I want to implement each formula in java to solve for m so that in this case I will end up with 2 answers. I have to do this as coding for each formula individually will be too time consuming for all the formulae I require.
So far my code below just detects and isolates each formula. I have also removed user input for the purposes of this question.
int y = 8;
int c = 2;
int x = 2;
try{
FileInputStream fstream = new FileInputStream("Filename");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine()) != null){
if(strLine.startsWith("Formula")){
String standAloneFormula = strLine.replace("Formula: ", "");
System.out.println(standAloneFormula);
}
}
}
catch(Exception e){
System.out.print(e);
The main problem that I am having is accessing the code and then applying the integer values to the string values. What would be the easiest way to solve for, in this case, m?
Any ideas, links or relevant code will be appreciated.
Regards.
Try creating a simple object model for equations using the composite pattern. You can break every input line down to being a single expression possibly containing other expressions as operands. Then you can define a method
calculate(HashMap<String, Integer> values)in all of your classes, wherevaluesis just the definition of all the variables that might occur in your calculation. By calling the method recursively you should in the end get the result.You will need one class for each mathematical operation you wish to support, e.g. Addition, Subtraction, Negation, …
Parsing the string and constructing the object hierarchy is the most difficult task actually. Would be a lot easier with a polish notation or something more easy to parse.
Overall it might be adviseable to use a tool more suited to solving mathematical problems rather than trying to code something yourself. Maybe even Excel might help.