nisaa15 0 Newbie Poster

How can one use recursion to get the following representations of a given word e.g. 'CARE':

C#ARE
AC#RE
RAC#E
ERAC#

Heres my attempt but i only manage to get the first representation, where does the recursive step need to go?

import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.Color;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;


public class ReadFile {


/** Creates a new instance of Main */
public ReadFile() {
}


public static void main(String[] args) {


ReadFile rf = new ReadFile();
try {
FileReader fr = new FileReader("THE LOCATION OF WHERE THE WORD FILE IS KEPT\\d.txt");
//creates a new filereader for the named file in the arguments
BufferedReader br = new BufferedReader(fr);


String record = new String();
while ((record = br.readLine()) != null) {
rf.reverseIt(record);
System.out.println(reverseIt(record));
}


} catch (IOException e) {
// catches possible io errors from readLine()
System.out.println("An IOException error has occured!");
e.printStackTrace();
}
}



public static String reverseIt(String s) {
String r = null;
for(int i = 0; i<s.length(); i++){
if(s.length() <= 1)
return s;
else{
r = (s.charAt(0) + "#" + s.substring(i, s.length()));
}


}
return r;
}

A file with 4 words is being read (the location of this file needs to be specified in the following line of code above FileReader fr = new FileReader("THE LOCATION OF WHERE THE WORD FILE IS KEPT\\d.txt");). the words im using are: AA, AB, CAR, CAT.

the current output im getting is:

compile:
run:
A#A
A#B
C#AR
C#AT
BUILD SUCCESSFUL (total time: 0 seconds)

however fro each word there should be n representations where n is the length of the word so for AA there should be A#A and AA#

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.