我的程序结构如下:一个代表原子概念的类,它基本上是一个String和另一个由一般概念列表组成的类。这两个类扩展了作为抽象类的类Concept,这意味着在列表中我可以同时嵌套原子概念和概念交集。 每个概念,原子或组成,都由toString方法打印出来。 粗略地说,这是基于这样的上下文无关文法:如何处理toString Java方法中的递归?
C : atom | (C and)+ C
凡Ç是抽象类的概念,原子是AtomicConcept和(C和)+ C是交叉口。
这是AtomicConcept类:
public class AtomicConcept extends Concept{
private String atomicConceptName;
public AtomicConcept(String c) {
this.atomicConceptName = c;
}
@Override
public String toString() {
return atomicConceptName;
}
}
这是车ConceptIntersection类:
import java.util.List;
public class ConceptIntersection extends Concept{
private List<Concept> list;
public ConceptIntersection(List<Concept> l) throws Exception {
if(l.size()>1)
{
this.list = l;
}
else
{
throw new Exception("Intersection needs at least two concepts!");
}
}
public String toString()
{
return Utils.conceptIntersection + Utils.lparen + Utils.splitConcepts(list) + Utils.rparen;
}
}
正如你在ToString函数看,我还创建了一个名为方法splitConcepts,它接受输入一般概念列表并返回由逗号分隔的每个概念组成的一个字符串。
public static String splitConcepts(List<Concept> list)
{
String result = "";
for (Concept item : list) {
System.out.println(item);
result += item.toString() + comma;
}
result = result.substring(0, result.length() - 1);
return result;
}
问题在哪里? 我有这个函数的麻烦,因为当我调用另一个嵌套的交集,这个函数永远不会结束!
一个例子:
public static void main(String[] args) throws DLRException {
// TODO Auto-generated method stub
AtomicConcept atom = new AtomicConcept("one");
AtomicConcept at = new AtomicConcept("two");
List<Concept> list = new LinkedList<Concept>();
list.add(at);
list.add(atom);
DLRConceptIntersection intersection = new DLRConceptIntersection(list);
System.out.println(intersection); // works fine
list.add(intersection);
DLRConceptIntersection intersection2 = new DLRConceptIntersection(list);
System.out.println(intersection2); //loop never ends!
}
是解决这个问题的一个正确的做法?
您有包括本身的交集。你想要打印什么? – user2357112
你是否知道你的'list'被共享? – user2357112