Search code examples
javafor-loopexpressionconditional-statementspalindrome

Conditional expression in for-loop doesn't act as expected


I can't seem to identify what is wrong with my code. After reading about the String class, I tried to print a palindrome backwards with a much shorter code, but I get nothing on the console except the execution of the newlines. And I think the problem might be from the conditional expression in the for statement because when I used "i <= l && i > -1" and debugged it with a System.print(i +" "), I got a list of numbers ranging from 17 to 0. So what could be wrong with the current expression, why can't I use "i < l && i > -1"? Is there something illegal about it because I intend to use numbers from 16 to 0 instead?

public class StephenWork
{
    private String objString ;
    private int index;

    private void makeString ( String objString)
    {
        this.objString = objString;
    }

    private char[] printBackwards ()
    {
        int length = objString.length();
        char [] backwards = new char [length];

        for (index = length ; index < length && index > -1 ; index-- )
        {
            backwards [index] = objString.charAt(index);
        }

        return backwards;   
    }

    public static void main (String ... args)
    {
        String palindrome = "tod saw I was dot";

        int l = palindrome.length();
        char [] backwards = new char [l];

        for ( int i = l; i < l && i > -1 ; i-- )
        {

            //System.out.println(i); //I was using this to debug the value of i
            backwards [i] = palindrome.charAt(i);
        }

        String printPalin = new String (backwards);
        System.out.println(printPalin);

        StephenWork example = new StephenWork ();
        example.makeString("I love Java");
        System.out.println( example.printBackwards());
    }
}

Solution

  • Index is set to the same value as length, so the loop won't execute because the condition is initially false.