2016-01-03 71 views
2

我试着写equals重写函数。我认为我已经写好了,但问题是解析表达式。我有一个数组类型ArrayList<String>它需要从键盘输入而不是评估结果。我可以与另一个ArrayList<String>变量进行比较,但我怎样才能比较ArrayList<String>String。例如,简单的数学表达式解析

String expr = "(5 + 3) * 12/3"; 
ArrayList<String> userInput = new ArrayList<>(); 
userInput.add("("); 
userInput.add("5"); 
userInput.add(" "); 
userInput.add("+"); 
userInput.add(" "); 
userInput.add("3"); 
. 
. 
userInput.add("3"); 
userInput.add(")"); 

然后转换userInput为字符串,然后比较使用等号 正如你看到的实在是太长了,当一个测试想申请。 我已经用来拆分,但它也拆分了组合数字。像1212

public fooConstructor(String str) 
{ 
    // ArrayList<String> holdAllInputs; it is private member in class 
    holdAllInputs = new ArrayList<>(); 

    String arr[] = str.split(""); 

    for (String s : arr) { 
     holdAllInputs.add(s); 
    } 
} 

正如你希望它不会给出正确的结果。它如何被修复?或者有人可以帮助编写正则表达式来正确解析它,正如所希望的那样? 作为输出我得到:

(,5, ,+, ,3,), ,*, ,1,2, ,/, ,3 

,而不是

(,5, ,+, ,3,), ,*, ,12, ,/, ,3 
+0

你如何添加12? 'userInput.add(“12”);''或'userInput.add(“1”);''userInput.add(“2”);'? – Guy

+0

'userInput.add(“12”);'@guy – askque

回答

3

正则表达式String.join

String result = String.join("", list); 

更多细节这里可以帮助你的是

"(?<=[-+*/()])|(?=[-+*/()])" 

当然,你需要避免不必要的空间。

在这里,我们走了,

String expr = "(5 + 3) * 12/3"; 
. 
. // Your inputs 
. 
String arr[] = expr.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])"); 
for (String s : arr) 
{ 
    System.out.println("Element : " + s); 
} 

请参阅我expiriment:http://rextester.com/YOEQ4863

希望它能帮助。

0
this makes all the inputs into one string which can then be can be compared against the expression to see if it is equal 

String x = "";  

for(int i = 0; i < holdAllInputs.length; i++){ 
    x = x + holdAllInputs.get(i); 
} 

if(expr == x){ 
    //do something equal 
}else{ 
    //do something if not equal 
} 
0

而不是分裂的输入令牌,你没有一个正则表达式,这将是很好的前进加入列表中的字符串如:

StringBuilder sb = new StringBuilder(); 
for (String s : userInput) 
{ 
    sb.append(s); 
} 

然后使用sb.toString()后来作比较。我不会建议字符串连接使用+运算符详细信息here

另一种方法是使用Apache Commons Lang中的StringUtils.join方法之一。

import org.apache.commons.lang3.StringUtils; 

String result = StringUtils.join(list, ""); 

如果你有幸使用Java 8是,那么它更容易...只是用这种方法可用here

+0

我的问题与ArrayList变量无关,它是关于fooConstructor中的字符串变量。解析字符串后,我可以构造然后比较。 – askque

+0

这就是我想说的。不要在'fooConstructor'中解析String变量。而是将列表中的字符串组合起来以进行比较。 (除非你想使用一些很难消化的正则表达式) –