E. Castillo
E. Castillo

Reputation: 37

How can i make the code print backwards recursively?

Here's my code. I am trying to make the String entered print out backwards, but every time I run it the code doesn't print out anything when it's called to print in reverse.

package Pali;

import java.util.Scanner;

/**
 * Created by alexa on 11/4/2016.
 */
public class Palindromes {
    public static void main(String[] args)
    {
        String msg;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a string: ");
        msg = scan.nextLine();
        System.out.print("\nThe string backwards: ");
        printBackwards(msg);
        System.out.println();
    }

    public static String printBackwards(String s)
    {
        if (s.length() == 0)
            return s;

        return printBackwards(s.substring(1)) + s.charAt(0);
    }
}

Upvotes: 0

Views: 297

Answers (4)

MaxZoom
MaxZoom

Reputation: 7753

Well you forgot to print letters

public static void printBackwards(String s)
{
    if (s.length() == 0) return ;
    printBackwards(s.substring(1));
    System.out.print(s.charAt(0));
}

DEMO

Upvotes: 2

xoxox
xoxox

Reputation: 798

printBackwards actually just returns a String, but does nothing else. To print that returned String you would have pass it to the println method.

public static void main(String[] args)
{
    String msg;
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a string: ");
    msg = scan.nextLine();
    System.out.print("\nThe string backwards: ");
    String reversed = printBackwards(msg);
    System.out.println(reversed);
}

Alternatively, you can let printBackwards print the String and leave the main method as it was:

public static String printBackwards(String s)
{
    if (s.length() == 0)
    {
        System.out.println(s);
        return s;
    }
    return printBackwards(s.substring(1)) + s.charAt(0);
}

Upvotes: 3

Einstein X. Mystery
Einstein X. Mystery

Reputation: 429

Your code calls printBackwards, but immediately discards the output.

Try changing line 6 of main() to System.out.print(printBackwards(msg));

Given that, I would also think about changing the method name to something like reverseString(String).

Upvotes: 0

Liam Larsen
Liam Larsen

Reputation: 150

Iteratively:

static String printBackwards(String s) {
   StringBuilder sb = new StringBuilder();
   for(int i = s.length() - 1; i >= 0; --i)
     sb.append(s.charAt(i));
   return sb.toString();
 }

Recursively:

static String printBackwards(String s) {
   if(s.length() == 0)
     return "";
   return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
 }

Upvotes: 0

Related Questions