Ansh Shrivastava Ansh Shrivastava - 17 days ago 6
Java Question

Printing Every Other Character Recursively

Hi StackOverflow users, I am currently taking a HS course on java, so I am a novice at java to say the least. Right now, for my own use, I am writing a program to accept a user input and print out every other letter recursively without any other classes imported but Scanner. My code works for odd numbers of characters, but not with even numbers of characters. Why is this, and can you suggest a simple fix without all these catch/throw things I don't understand? My code is posted below. Thanks, -A Novice Java Coder

import java.util.Scanner;
public class PrintChars
{
private String chunk;
public PrintChars ( )
{
chunk = "";
}

public static void main ( String [] args )
{
PrintChars p = new PrintChars ( );
p.GetPhrase ( );
p.Deconstruct ( );
}

public void GetPhrase ( )
{
Scanner console = new Scanner ( System.in );
do
{
System.out.print ( "\n\nEnter a phrase: " );
chunk = console.nextLine ( );
} while ( chunk == null );
System.out.println ( "\n\n" );
}

public void Deconstruct ( )
{
OneChar ( chunk );
System.out.println ( "\n\n" );
}

public int OneChar ( String c )
{

if ( c.equals ( "" ) )
return 1;
else
{
char first = c.charAt ( 0 );
c = c.substring ( 2 );
System.out.println ( first );
return OneChar ( c );
}
}
}

Answer

Looks like you need to check c before you try and substring it... If it's length is less then 2, you'll get a StringIndexOutOfBoundsException, because you're trying to substring starting at index 2, but index 2 doesn't exist. Try this:

public int OneChar ( String c )   
    {

        if ( c.equals ( "" ) )
            return 1;
        else   
        {
            char first = c.charAt ( 0 );
            System.out.println ( first );
            if(c.length() > 2) {
                c = c.substring ( 2 );
                return OneChar ( c );
            }
            return 1;
        }
    }
Comments