I was tasked to make a program that took a string input, then reversed it using recursion. I'm getting a syntax error causing an exit code 1. Also, I'm sure there may be an error in the code as I'm not very strong with recursion. Any help with this (specifically this obnoxious syntax error which I can't seem to find) would be very helpful!

/**
This program takes a string input and
reverses is using recursion, then
outputs it
*/

import java.util.Scanner;
import java.util.*;

public class StringReverser
{
    public static void main(String[] args)
    {
        String input;
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter a string to be reversed: ");
        input = keyboard.nextLine;

        reverse(input);
    }

    public static String reverse(String str)
    {
        if((null == str) || (str.length() <= 1))
        {
            return str;
        }

        return reverse(str.substring(1)) + str.charAt(0);
    }
}

change line 18 input = keyboard.nextLine; with
input = keyboard.nextLine();

Edited 2 Years Ago by dlarytm

try this code

String input,output;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a string to be reversed: ");
input = keyboard.nextLine();//change to method
output=reverse(input);
System.out.println("The reversed string is: ");
System.out.println(output);

Naresh. It's good that you want to help, but your post exactly duplicates the solution given by dlarytm two days ago.
Please take a moment to read the whole thread before posting, and ensure that your posts always add something new.
Thank you.

This article has been dead for over six months. Start a new discussion instead.