2017-06-04 61 views
-2

我想知道如何通过使用递归从文件中读取文本(包含Java代码)来正确缩进问题。原始输出将没有任何 选项卡。使用递归进行识别

这是我们的目标:enter image description here

这是代码,但我需要去适应它从一个文本文件阅读:

void indent(int m, int n) 
{ 
    System.out.println(m); // Forward Printing 

    if (m < n) 
    { 
    indent(m + 1, n); 
    System.out.println(m); // Backward Printing 
    } 
} 
+0

使用'astyle','indent'或'ide'。大多数(全部),其中可以做到这一点。 –

+0

@Elliott必须递归 – Mesutluka1019

+0

你试过了什么(显示[mcve])?你卡在哪里,它有什么问题? –

回答

0

好了,该算法可以像......

function indent(theText, indentCharCount) { 
    for each character of the text... 
     if it is an end-of-line character... 
     concatenate spaces to return string using indentCharCount 
     else if it is a '{' character... 
     scan ahead through characters to find matching '}' character 
     recursively call indent() function passing... 
      characters between { and } for 'theText' param 
      indentCharCount+2 for 'indentCharCount' param 
     concatenate return value of indent() to return string 
     set loop index so that the next character will be the matched '}' 
     else (it's some other character) 
     concatenate character to return string 
    return the concatenated string 
} 

我不想写出Java中的所有代码。如果你正在做家庭作业,我宁愿你学到一些东西!但是,这是一个基本的递归算法,我相信这符合你的问题。

+1

如果'theText'是'Reader'的一个实例,则不需要提前扫描,因为递归调用返回时,Reader将位于右括号之后的字符处。 – SpiderPig

+0

非常有帮助的先生!我会试着去实现它。 – Mesutluka1019