我正在学习java并尝试使用Stack的例子。这是代码:
import java.util.*;
public class StackTry {
static boolean checkParity (String expression,
String open, String close) {
Stack stack = new Stack();
StringTokenizer st = new StringTokenizer (expression, " \t\n\r\+/-(){}", true);
while (st.hasMoreTokens()) {
String tmp = st.nextToken();
if (tmp.equals(open)) stack.push(open);
if (tmp.isEmpty()) return true;
return false;
}
public static void main (String [] args) {
System.out.println (
checkRarity("a - (b - (c - a) / (b + c) - 2), "(", ")));
}
}
}
我在7行收到错误,如何解决?
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
我按照建议编辑了代码,但是
Multiple markers at this line
- The method checkRarity(String, String) is undefined for the type
StackTry
- Syntax error on token ""a - (b - (c - a) / (b + c) - 2), "", , expected after
this token
答案 0 :(得分:3)
错误是由于\+
。
在Java中,以\
开头的任何内容都被视为转义序列的开头,而\+
不是有效的转义序列。放弃\
,因为您不必逃离+
。
答案 1 :(得分:2)
在你的字符串中,你似乎试图逃避+
符号,你不必这样做,这就是你得到错误的原因。应该是这样的:
StringTokenizer st = new StringTokenizer (expression, " \t\n\r+/-(){}", true);
您可以直接指定+
,如果您尝试在StringTokenizer
中提供反斜杠,则必须使用双反斜杠\\