Kurt16
Kurt16

Reputation: 35

Why do i get this error message when using recursion?

I got this message: the left-hand side of an assignment must be a variable when i finished to resolve an excercise about printing a string reversely in recursively-looping. I just want to know if someone could provide an explanation of it? The error message appears in the last line...I don't understand, WHY? There is my code:

import java.util.Scanner;

public class Excersise {

    public static void main(String[] args) {

        // Create a Scanner
        Scanner input = new Scanner(System.in);
        //Prompt the user to enter a string
        System.out.print("Enter a string: ");
        String s = input.nextLine();
        reverseDisplay(s);

    }

    public static void reverseDisplay(String value) {

        //Base case
        if (value.length() < 2) { 
            System.out.println(value);
        } else {
            //Recursion
            reverseDisplay(value.substring(1)) + value.charAt(0); <--error

        }
    }
}

Upvotes: 0

Views: 232

Answers (2)

Brian
Brian

Reputation: 7326

You need to change return type of your method to String and return it and print in your main method

public class Exercise{

public static void main(String[] args) {

    // Create a Scanner
    Scanner input = new Scanner(System.in);
    //Prompt the user to enter a string
    System.out.print("Enter a string: ");
    String s = input.nextLine();
    System.out.println(reverseDisplay(s));

}

public static String reverseDisplay(String value) {

    //Base case
    if (value.length() < 2) { 
        return value;
    } else {
        //Recursion
        return reverseDisplay(value.substring(1)) + value.charAt(0);

    }
}

}

Upvotes: 0

McLovin
McLovin

Reputation: 3674

import java.util.Scanner;
public class Exercise {
    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);
        //Prompt the user to enter a string
        System.out.print("Enter a string: ");
        String s = input.nextLine();
        reverseDisplay(s);
        System.out.println();
    }
    public static void reverseDisplay(String value) {
        //Base case
        if (value.length() < 2) { 
            System.out.print(value);
        } else {
            //Recursion
            //calls for string without first char
            reverseDisplay(value.substring(1));
            //prints first char
            System.out.print(value.charAt(0));
        }
    }
}

This works. Your approach to recursion was on the right track, but you want to print the first character after calling the method on the rest of the string. I also added another println at the end of main so the reversed string would appear on its own line.
The compiler error you got was because the compiler thought that the line was supposed to be an assignment (likeint a = b + c) and didn't see an =.

Upvotes: 1

Related Questions