我写的代码依赖于给定的标签顺序是 "NUMBER" "MATH" "NUMBER" "MATH" "NUMBER" 并且它完全忽略了 math 中的操作规则。它只是您可以做的一个大纲,因此您可能需要对其进行一些修复才能做您想做的事情。
由于时间不够,我没有测试这个文件,所以如果有必要调试它!
import net.sprakle.homeAutomation.interpretation.tagger.tags.*;
import java.util.List;
import java.util.Arrays;
public class Math {
private Tag[] tags; //Stores the converted tags as a "MathTag"
//Requires an array of tags
public Math(Tag[] inputTags) {
tags = new MathTag[inputTags.length]; //create a new MathTag array
System.arraycopy(inputTags, 0, tags, 0, tags.length); //Convert Tag array to MathTag array
}
//returns a value based on the tags
//TODO: ADD MATHEMATICAL ORDER OF OPERATIONS!!!
public double performMath() {
double value = 0;//initial value to return
for (int i = 0; i < tags.length; i++) { //perform initial check of the phrase given
if (tags[i].getType() = TagType.NUMBER && !tags[i].getWasChecked() && i + 1 < tags.length) {
value = performOperation(i, value, Double.parseDouble(tags[i].getValue()), tags[i+1].getType());
} else if (tags[i].getType() = TagType.MATH && !tags[i].getWasChecked() && i + 1 < tags.length) {
value = performOperation(i, value, Double.parseDouble(tags[i + 1].getValue()), tag.getType()); //I'm not positive if this would not cause issues
}
}
}
//Perform individual operations given the index of the operation, value1, value2, and the operation type
//The order of the array "operations" must match the order of the operations in the switch statement.
public double peformOperation(int i, double value1, double value2, String operation) {
String[] operations = {"add", "subtract", "multiply", "divide", "pwr", "root"}; //Array of operations
List list = Arrays.asList(operations); //Not exactly effecient, used to check what operation to perform
switch (list.indexOf(operation)) { //Perform a task based on the operation
case 0: //Addition
tags[i].setChecked(true); //Number
tags[i + 1].setChecked(true); //Operation
return value1 + value2;
case 1: //Subtraction
tags[i].setChecked(true); //Number
tags[i + 1].setChecked(true); //Operation
return value1 - value2;
case 2: //Multiplication
tags[i].setChecked(true); //Number
tags[i + 1].setChecked(true); //Operation
return value1 * value2;
case 3: //Division
tags[i].setChecked(true); //Number
tags[i + 1].setChecked(true); //Operation
return value1 / value2;
case 4: //Power
tags[i].setChecked(true); //Number
tags[i + 1].setChecked(true); //Operation
return value1 * value1;
case 5: //Square Root
tags[i].setChecked(true); //Number
tags[i + 1].setChecked(true); //Operation
return Math.sqrt(value1);
}
return error(); //Non-valid operation found
}
//Need some way to detect an error
public double error() {
return 0;
}
//Need some way to check if a tag was looked at before
class MathTag extends Tag {
protected static boolean wasChecked = false;
public void setChecked(boolean checked) {
wasChecked = true;
}
public boolean getWasChecked() {
return wasChecked;
}
}
}