Print recursively without any loops

Axwell Smith :

Didn't find any other post like this so i had to ask. It is easy to print anything... but when you're not allowed to use iterative methods then things get tricky.

My problem is that i have two methods in one class. This class has a string that should be printed in reverse.. simple with iterative methods but not when char and int gets in the way,

I have tried to count the amout of integers to the amout of char in a string and then use the other method to take that same string and count of int to print it out in reverse.

NOTE: Need these two methods with string and int as parameters.

What am i doing wrong?

public class PrintRecursive {
private static int j;

public static void main(String[] args) {

    String str = "Hello Everyone!";

    print(str, 0);
    System.out.println(); // Line break
    printReverse(str, 0);
}

private static void printReverse(String str, int i) {
    char ch = (char) i;
    if (ch == ' ') {

    } else
        while (str.contains(str)) {
            i += str.charAt(ch);
        }
}

private static void print(String str, int i) {

    while (str.equals(i)) {
        System.out.println(str.charAt(j--));
    }
}

}

Outcome:

Hello Everyone! !enoyrevE olleH

ALSO: Note that i guess that i should be talking to the methods directly instead of my "private int j".

My code atm is not recursive!!!!!!! But i want it to be but i cannot figure out a way of doing so.

CyB3RC0nN0R :

A recursive approach (where one letter is printed in each recursion step) could look like this:

private static void print(String s, int i) {
    if(i == s.length() - 1)   
        System.out.println(s.charAt(i));
    else {
        System.out.print(s.charAt(i));
        print(s, i+1);
    }
}

private static void printReverse(String s, int i) {
    if(i == 0)
        System.out.println(s.charAt(0));
    else {
        System.out.print(s.charAt(i));
        printReverse(s, i-1);
    }
}

You would call it as follows:

public static void main(String[] args) {
    print("abcd", 0);
    printReverse("abcd", 3);
}

print() is passed the integer 0 as a starting value and printReverse() is passed the length of the string - 1, which is the index of the last letter.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148010&siteId=1