【发布时间】:2017-02-24 02:12:53
【问题描述】:
我很难在字符串中获取正确的标记。我只能取 (false,true,or,and,not,),()) 之类的标记。如果字符串中的标记是“(假”,那么我需要返回“(”和“假”)。这就是我遇到问题的地方。
例如,我想要的输出是:
line: [ not (false or error true) ]
next token: [not]
next token: [(]
next token: [false]
next token: [or]
next token: [true]
next token: [)]
但我的输出是:
line: [ not (false or error true) ]
next token: [not]
next token: [(]
next token: [or]
next token: [true]
next token: [)]
在迭代扫描“or”的下一个标记时,我之前已经返回了“(”并且我的下一个标记是“false”,但我不知道如何返回它。它跳过它并返回“or” .
这是我的方法。
public boolean hasNext() {
if(!scan.hasNext()){
return false;
}
return true;
}
public String next() {
while(scan.hasNext()){
scan.useDelimiter(" ");
otherToken = scan.next();
if(otherToken.contains("(") || otherToken.contains(")")){
if(otherToken.contains("(")){
nextToken = otherToken.substring(1, otherToken.length());
return "(";
}
if(otherToken.contains(")")){
nextToken = ")";
return otherToken.substring(0, otherToken.length()-1);
}
}
if(otherToken.equals("true") || otherToken.equals("false") ||
otherToken.equals("or") || otherToken.equals("and") ||
otherToken.equals("not")){
nextToken = otherToken;
return nextToken;
}
if(otherToken.equals("(") || otherToken.equals(")")){
nextToken = otherToken;
return nextToken;
}
else{
continue;
}
}
return nextToken;
}
【问题讨论】:
-
你为什么不想要“错误”作为标记?如果它是一个令牌,那么不仅解决方案会很简单,而且您将了解“错误”在您的令牌中的位置——您将如何找到“错误”令牌的来源??
-
错误不是我的程序的有效令牌,所以我忽略它
-
那么,你想要的token之间可以有任意的“垃圾”吗?
-
是的,我只需要我在上面的问题中列出的有效问题