2012-07-30 62 views
0

我有recrusive功能工作正常。问题是当行数很大时它给出了stackoverflow错误。我想把它放在迭代中,可能使用for循环。在做这件事时需要一些帮助。该方法的更改递归方法迭代

private TreeSet validate(int curLine, TreeSet errorSet) { 
    int increment = 0; 
    int nextLine = 0; 

    if (curLine == lines.length || errorSet.size() != 0) { 
     return errorSet; 
    } else { 
     String line = lines[curLine]; 

     //validation starts. After validation, line is incremented as per the requirements 

     increment = 1 //As per requirement. Depends on validation results of the line 

     if (increment > 0) { 
      try{ 
       Thread.currentThread().sleep(100); 
      }catch(Exception ex){ 
       System.out.println(ex); 
      } 
      nextLine = (curLine + increment); 
      validate(nextLine, errorSet); 
     } 
    } 

    return errorSet; 
} 

海报的描述:

的方法确实验证文本行,这些行有多少行已被跳过,如果该行是有效的指令。所以,如果该行是有效的,许多行将被跳过使用增量。如果行是无效的增量将是0

+1

您正在调用'validate(nextLine,errorSet)'而不保存其返回值。这是故意的吗?另外,由于前面的行,'if(increment> 0)'总是成立的:'increment = 1'。解释该方法应该做什么可能是一个好主意。 – 2012-07-30 16:12:40

+0

它工作正常,所以我没有保存它。 – FirmView 2012-07-30 16:17:17

+0

增量不会总是> 0.如果行中有错误,则增量为0. – FirmView 2012-07-30 16:19:15

回答

2

我不知道为什么,这是摆在首位不断递归。这非常适合使用FOR循环。使用像这样:

private TreeSet validate(int curLine, TreeSet errorSet) { 
    int increment = 0; 

    if (errorSet.size() != 0) 
     return errorSet; 

    for (int curLine = 0; curLine < lines.Length; curLine += increment) 
    { 
     // put your processing logic in here 


     // set the proper increment here. 
    } 
} 

如果增量总是将是1,那么你可以只用curr++代替curLine += increment

1
for(String line : lines) { 
    // validate line here 

    if(!errorSet.isEmpty()) { 
    break; 
    } 
} 
1

你的问题的解决方案可能是简单的for循环或while ,用于停止条件的逻辑表达式。通常,当我们必须通过Iterable或数组的所有元素时,我们使用for循环。如果我们不知道我们要做多少循环,我们使用while循环。对于遍历时的优势,是我们的自由已经局部变量,所以我们没有CA他们使用圈外的一面,因此,我们减少的可能性有一些bug。

您的问题是,你必须打破两个条件的程序:

  1. 当errorSet不是空的。
  2. 当线的阵列具有不再项目。

至于矛盾,我们可以说,你的程序应该继续:

  1. 直到errorSet是空的,
  2. ,直到行数小于它们的存储阵列的尺寸。

这为我们提供了简单地表达

  1. errorSet.isEmpty()
  2. lineNumber < lines.length()

我们可以通过逻辑运算符&&将它们组合起来,并在for循环停止规则中使用。

for(int lineNumber= 0; errorSet.isEmpty() && lineNumber< lines.length(); lineNumber++) { 

    //code to operate 

} 

注:

典型地,对于逻辑表达式被用于操作者&&,即确保该逻辑表达式的每一个部分进行评价。这另一种方法是&,在虚假的情况下,不要操作时间更长,返回false。我们可能会试图使用这个运算符来表达这个表达式,但我会是个坏主意。因为当我们遍历所有行而没有错误时,代码将生成IndexOutOfBoundException,如果我们切换位置,那么我们不会有任何优化,因为第一个表达式将被评估的次数相同。