0

我的教授给了我们一个任务,让我们编写一个可以做很多事情的程序。该程序要做的一件事是浏览一个.txt文件,并返回您指定的单词的所有实例以及它们所在的行。例如,如果这是文本文件:

这是一个测试。
测试word文件。
这将被视为测试。

运行该方法并搜索单词“test”后,您应该会收到类似以下内容:

1: This is a test.       
3: This will be considered a test.

现在这是我的问题。他希望我们用递归的方法来做,我不知道如何启动这个方法。我知道对于递归方法,您必须在每次调用它时调用自身并减少,但是,此方法的参数是一个单词。说我有:

String getTheWord (String word) {     
    if (word == 0){    //which still wouldn't compile, so I think I should use word == null     
        // something    
    }

    //something smart here      

    return getTheWord(word - 1); // which wouldn't compile
}

那么我该怎么写呢?我想我必须为参数使用一个字符串,因为我怎么知道我要找的词是什么?或者也许我错了,任何帮助!

4

2 回答 2

1

尝试类似:

public String getTheWord(String textToSearch, String searchingFor,
  int currentLineNumber) {

    // Separate the text into lines.
    String[] lines = textToSearch.split('\n');

    // Get the first line of the (remaining) text.
    String firstLine = lines[0];

    // We're going to have some result from this method call: either
    // an empty string or a message indicating that we found the word.
    String resultFromThisLine = "";        

    // Now, look for the word.
    if (firstLine.contains(searchingFor)) {
        // We found it.
        resultFromThisLine = currentLineNumber + ": " + firstLine + "\n";
    }

    // Now we check to see if there are any lines left.
    if (lines.length == 1) {
        // This was the last line.
        return resultFromThisLine;
    } else {
        // There are more line(s).
        // Create a string with all lines but the first one.
        String remainingLines = "";
        for (int i=1; i<lines.length; i++) {
            remainingLines += lines[i] + "\n";
        }


        // Here's the key part.
        // Take the result from this line, add it to the result from the
        // next line, and return *that*.

        return resultFromThisLine + getTheWord(remainingLines, searchingFor,
          currentLine + 1);

     }
}
于 2013-03-10T01:54:40.623 回答
1

首先我们应该问,为什么我们要使用递归来解决这个问题。在Introduction to Computer Science - Java页面中,我们可以找到一些描述递归解决方案的特征:

  1. 一个简单的基本案例,我们有一个解决方案和一个返回值。
  2. 一种使我们的问题更接近基本情况的方法。即一种切掉部分问题以获得更简单的问题的方法。
  3. 将更简单的问题传递回方法的递归调用。

对我来说,你的问题根本不符合这个特征。

但是好吧,你不想这样做——你必须这样做。

首先你应该考虑模型,它可以代表你的问题。我创建了简单的Line类,它存储行号和行。

class Line {

    private int number;
    private String text;

    public Line(int number, String text) {
        this.number = number;
        this.text = text;
    }

    public int getNumber() {
        return number;
    }

    public String getText() {
        return text;
    }

    @Override
    public String toString() {
        return number + " : " + text;
    }
}

然后,您应该在使用简单循环的地方创建解决方案。

class LoopSearcher {

    public List<Line> findLines(String text, List<String> lines) {
        List<Line> matchLines = new ArrayList<Line>();
        int index = 0;
        for (String line : lines) {
            index++;
            if (line.contains(text)) {
                matchLines.add(new Line(index, line));
            }
        }
        return matchLines;
    }
}

您可以通过以下方式对其进行测试:

List<String> lines = IOUtils.readLines(new FileInputStream(new File(
        "D:/test.txt")));

List<Line> loopLines = new LoopSearcher().findLines("test", lines);

for (Line line : loopLines) {
    System.out.println(line);
}

现在,如果我们有循环解决方案,我们可以将其修改为递归解决方案:

class RecursiveSearcher {

    LinkedList<Line> matchLines = new LinkedList<Line>();

    public List<Line> findLines(String text, List<String> lines) {
        if (lines.isEmpty()) {
            return matchLines;
        }

        int number = lines.size() - 1;
        String line = lines.remove(number);
        if (line.contains(text)) {
            matchLines.addFirst(new Line(number + 1, line));
        }
        return findLines(text, lines);
    }
}

您可以通过以下方式对其进行测试:

List<String> lines = IOUtils.readLines(new FileInputStream(new File(
        "D:/test.txt")));

List<Line> recursiveLines = new RecursiveSearcher().findLines("test",
        lines);
for (Line line : recursiveLines) {
    System.out.println(line);
}

如您所见,我创建了带有 to 参数的方法:

  1. text - 我们要在每一行中找到的文本
  2. 行 - 文件中所有行的列表。当然,你可以提供 raw String,它可以代表所有文件内容。
于 2013-03-10T02:12:58.127 回答