如何递归地执行相同的操作并仍然使用扫描仪和集合?

发布于 2025-01-12 13:57:43 字数 645 浏览 0 评论 0原文

这是我使用集合和扫描仪参数创建的代码。我一直很困惑将它结合到递归中,我使用了迭代。

public class Main {
  public static void main(String[] args) {
    Deque deque = new LinkedList<>();

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter your words (type R to reverse):");

    while(sc.hasNext()) {
      String line = sc.next();
      if(line.toLowerCase().equals("r")) {
        break;
      }
      deque.add(line);
    }

    System.out.println("\n===== Reversed Lines =====\n");        

    Iterator reverse = deque.descendingIterator();
    while (reverse.hasNext()) {
      System.out.println(reverse.next());
    }
  }
}

Here's the code I have created using the collection and the scanner parameters. I've been so confused to combine it into recursive, I used iteration.

public class Main {
  public static void main(String[] args) {
    Deque deque = new LinkedList<>();

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter your words (type R to reverse):");

    while(sc.hasNext()) {
      String line = sc.next();
      if(line.toLowerCase().equals("r")) {
        break;
      }
      deque.add(line);
    }

    System.out.println("\n===== Reversed Lines =====\n");        

    Iterator reverse = deque.descendingIterator();
    while (reverse.hasNext()) {
      System.out.println(reverse.next());
    }
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

殤城〤 2025-01-19 13:57:43

首先,快速回顾一下递归

每个递归方法都由两部分组成:

  • 基本情况 - 表示一个简单的边缘情况(递归终止时的条件),其结果是预先知道的。
  • 递归案例 - 解决方案的一部分,进行递归调用,并且主要逻辑驻留在其中。

您可以将负责读取用户输入的代码提取到单独的方法中,并用递归调用替换while循环。

基本情况由两种情况表示:sc.hasNext() 产生 false 并且用户输入等于 "r"< /代码>。否则,该行将被添加到队列中,并进行新的递归调用。

从队列中打印内容也可以递归地完成。此方法的基本情况是当reverse.hasNext()返回false时。在递归情况中,将打印下一个元素,并进行后续的递归调用。

因此,为了能够使用 ScannerQueue,您可以将它们作为参数传递或使它们全局可访问。

由于此任务的要求,ScannerQueue 在方法 readAndPrint() 内部本地声明,并作为方法 的参数读取输入()。

public class Main {

    public void readAndPrint() {
        Scanner sc = new Scanner(System.in);
        Deque<String> deque = new LinkedList<>();
        System.out.println("Enter your words (type R to reverse):");
        readInput(sc, deque); // recursive helper-method that read from the console

        System.out.println("\n===== Reversed Lines =====\n");
        print(deque.descendingIterator()); // recursive helper-method that prints to the console
    }

    public static void print(Iterator<String> reverse) {
        if (!reverse.hasNext()) { // base case
            return;
        }

        System.out.println(reverse.next());
        print(reverse); // recursive call
    }

    public void readInput(Scanner sc, Deque<String> deque) {
        if (!sc.hasNext() && sc.hasNextLine()) { // no more input on this line, but there's at least one more line
            sc.nextLine(); // advance to the next line
        }
        if (!sc.hasNext()) { // base case
            return;
        }
        String line = sc.next();
        if (line.equalsIgnoreCase("r")) { // base case
            return;
        }
        deque.add(line);
        readInput(sc, deque); // recursive call
    }
    
    public static void main(String[] args) {
        ri.readAndPrint();
    }
}

输出

Humpty Dumpty    // multyline input
sat on a wall R

===== Reversed Lines =====

wall
a
on
sat
Dumpty
Humpty

First of all, quick recap on recursion.

Every recursive method consists of two parts:

  • Base case - that represents a simple edge-case (condition when recursion terminates) for which the outcome is known in advance.
  • Recursive case - a part of a solution where recursive calls are made and where the main logic resides.

You can extract the code responsible for reading the user input into a separate method and substitute the while loop with the recursive call.

The base case is represented by two situations: sc.hasNext() yields false and user input is equal to "r". Otherwise, the line will be added to queue and a new recursive call will be made.

And printing the content from the queue could be done recursively as well. The base case for this method is when reverse.hasNext() returns false. In the recursive case the next element will be printed, and a subsequent recursive call will be made.

So in order to be able to use Scanner and Queue you can either pass them as parameters or make them accessible globally.

Because of the requirements for this task, Scanner and Queue are declared locally inside the method readAndPrint() and as parameters of the method readInput().

public class Main {

    public void readAndPrint() {
        Scanner sc = new Scanner(System.in);
        Deque<String> deque = new LinkedList<>();
        System.out.println("Enter your words (type R to reverse):");
        readInput(sc, deque); // recursive helper-method that read from the console

        System.out.println("\n===== Reversed Lines =====\n");
        print(deque.descendingIterator()); // recursive helper-method that prints to the console
    }

    public static void print(Iterator<String> reverse) {
        if (!reverse.hasNext()) { // base case
            return;
        }

        System.out.println(reverse.next());
        print(reverse); // recursive call
    }

    public void readInput(Scanner sc, Deque<String> deque) {
        if (!sc.hasNext() && sc.hasNextLine()) { // no more input on this line, but there's at least one more line
            sc.nextLine(); // advance to the next line
        }
        if (!sc.hasNext()) { // base case
            return;
        }
        String line = sc.next();
        if (line.equalsIgnoreCase("r")) { // base case
            return;
        }
        deque.add(line);
        readInput(sc, deque); // recursive call
    }
    
    public static void main(String[] args) {
        ri.readAndPrint();
    }
}

Output

Humpty Dumpty    // multyline input
sat on a wall R

===== Reversed Lines =====

wall
a
on
sat
Dumpty
Humpty
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文