Home > front end >  How to do the the same thing recursively and still using Scanner and a Collection?
How to do the the same thing recursively and still using Scanner and a Collection?

Time:03-09

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.

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;

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());
    }
  }
}

CodePudding user response:

Here is a method that uses recursion to reverse a string. A brief explanation is provided but to fully understand recursion it is best to carefully follow the code and write out each step on paper.

  • if the string is empty, then "" is returned, and subsequent calls to reverse will start to return.
  • otherwise, call reverse with the substring skipping the first character.
  • when reverse finally returns from all the call, it will append the first character in the string of the call stack to the beginning of the string, thus reversing it.
public static String reverse(String s) {
    while(!s.isEmpty()) {
        return reverse(s.substring(1))   s.charAt(0);
    }
    return "";
}

It is up to you how you use this in your overall program.

Note: Rewriting the above as follows may make it clearer. They do the same thing.

public static String reverse(String s) {
    while(!s.isEmpty()) {
        String r = reverse(s.substring(1));
        return r   s.charAt(0);
    }
    return "";
}

CodePudding user response:

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 a made and when 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.

I placed all this logic into a separate class, where Scanner and Queue are declared as instance field.

public class ReversedInput {
    private final Scanner sc = new Scanner(System.in);
    private final Deque<String> deque = new LinkedList<>();

    public void readAndPrint() {
        System.out.println("Enter your words (type R to reverse):");
        readInput(); // 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 void print(Iterator<String> reverse) {
        if (!reverse.hasNext()) { // base case
            return;
        }

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

    public void readInput() {
        if (!sc.hasNext()) { // base case
            return;
        }
        String line = sc.next();
        if (line.equalsIgnoreCase("r")) { // base case
            return;
        }
        deque.add(line);
        readInput(); // recursive call
    }
}

Main class

public class Main {
    public static void main(String[] args) {
        ReversedInput ri = new ReversedInput();
        ri.readAndPrint();
    }
}

Output

Humpty Dumpty sat on a wall R

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

wall
a
on
sat
Dumpty
Humpty
  • Related