Results 1 to 2 of 2
  1. #1
    Codeless is offline Member
    Join Date
    Nov 2010
    Posts
    37
    Rep Power
    0

    Default How does this very simple code work?

    This is a simple recursion program which reverses the order of characters in a word

    Java Code:
    public class Main 
    {
    
    public static String reverse(String str)
    {
    	if (str.equals(""))
    	{
    		return "";
    	}
    	else
    	{
    		char first = str.charAt(0);
    		String part = str.substring(1);
    		return reverse(part)+ first ;
    		
    	}   												 
    }
    	
    public static void main (String[] args)
    {
    System.out.print(reverse("cat"));
    }
    my question is waht happens here
    Java Code:
    return reverse(part)+ first ;
    because to me it looks like it should print the word in the same order, the value of "first" is c, then the next time through it becomes a... so why does it print tac? and not cat?

  2. #2
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    because you append the first character to the end of the string sequence.
    Ever seen a dog chase its tail? Now that's an infinite loop.

Similar Threads

  1. Simple file reader won't work in eclipse
    By BoomPony in forum New To Java
    Replies: 3
    Last Post: 11-27-2010, 06:16 PM
  2. Will this code work
    By rajat16 in forum XML
    Replies: 3
    Last Post: 09-24-2010, 12:52 PM
  3. Replies: 4
    Last Post: 08-23-2010, 04:19 AM
  4. My Simple Array Does Not Work!
    By Simplev_v in forum New To Java
    Replies: 16
    Last Post: 09-07-2009, 03:43 PM
  5. Simple animation won't work
    By nolsen01 in forum New To Java
    Replies: 4
    Last Post: 07-09-2009, 12:36 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •