给定一个ArrayList形式:
{ "(", "2", "+", "4", ")", "/", "2"}
我想访问括号之间的所有项目,然后对这些项目运行一个方法。
为此,我将不得不说:
while(arrayList.contains("(")&&arrayList.contains(")")){
// access the items between the brackets
}
括号不会总是在相同的位置,并且它们之间会有不同数量的项目。我将如何访问这些项目?
您需要获取数组列表中括号的索引。对于您使用的数据结构,我认为应该查看 javadoc 以获取有关您可以使用它做什么的信息。ArrayList.contains() 是 ArrayList 的一个有用方法,但是 ArrayList.indexOf() 在这种情况下会更有用。
public int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1
if this list does not contain the element. More formally, returns the lowest index i
such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
使用这种方法,您可以获得两个连续的开闭括号的索引,当然,如果它们存在的话。获得索引后,您可以在它们之间进行迭代。这是一种解析工作,因此您可能会通过尝试实现一些递归方法来弄脏您的手。例如,{“(”,“(”,“2”,“+”,“4”,“)”,“ /"、"2"、")"}。对于这样的嵌套语句,您应该进行更多研究。
您应该需要知道的是复杂语句的树。我强烈建议您检查树数据结构。
编辑:您还可以找到许多针对此问题的堆栈实现。关键词:栈表达式解析器算法。
使用这样的东西
String exp=/*ArrayList.toString()*/
exp=exp.replace(",","");
exp=exp.replace("[","");
得到表达式后
您可以使用内置的 Javascript 引擎。
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Test {
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
}
}
参考:堆栈溢出
你可以这样做:
ArrayList<String> list; // The list you want to process
for (int i = list.indexOf("(") + 1; i < list.indexOf(")"); i++) {
// Do something with list.get(i)
}
这仅适用于恰好出现一次“(”和“)”,但您可以根据需要轻松修改代码。