0

My program is supposed to generate a pattern of letters based on the input of the user. I have to use recursion to set each output to be different. I've already done this. Next i have to compare the two outputs in another method and use recursion to find the length of the longest common sub sequence between the two. The problem is i dont know how to compare them. Since they are void results i dont know how to convert them to strings.

 import java.util.Scanner;
public class patternOfLetters {
private static String letter;

public static void printLetterPattern(char letter){
    char [] pattern = new char[1];
    int patternLength= pattern.length;
    String result="";
    char start=letter;
    if(start=='A'){
        System.out.print('A');
        result+='A';
    }else if(start=='B'){
        printLetterPattern('A');
        System.out.print('B');
        printLetterPattern('A');
    }
    else if(start=='C'){
        printLetterPattern('B');
        System.out.print('C');
        printLetterPattern('B');
    }
    else if(start=='D'){
        printLetterPattern('C');
        System.out.print('D');
        printLetterPattern('C');
    }
}


public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    Scanner otherIn = new Scanner(System.in);
    System.out.println("Enter a character to start the pattern: ");
    String input = in.nextLine(); 
    String upper = input.toUpperCase();
    char letter=upper.charAt(0);
    System.out.println("");
    System.out.println("Your first pattern of letters is:");
    printLetterPattern(letter);
    System.out.println("");
    System.out.println("");

    System.out.println("Enter another character to generate your second pattern: ");
    String input2 = in.nextLine(); 
    String upper2 = input2.toUpperCase();
    char letter2=upper2.charAt(0);
    System.out.println("");
    System.out.println("Your second pattern of letters is:");
    printLetterPattern(letter2);

in.close();
otherIn.close();
}

}//fin.

crashmstr
  • 28,043
  • 9
  • 61
  • 79

1 Answers1

2

You cant, return type "void" means there is no result returned, so there is nothing you could convert.

Your methods just print their output to the console, you will need to rewrite them so they actually return a result.

One way could be like this (pseudocode):

public String produceLetterPattern(String pattern, char letter) {
    ...
    if(start=='A') {
        pattern+="A";
        return pattern;
    } else if (start=='B') {
        pattern = produceLetterPattern(pattern, 'A');
        pattern +="B";
        pattern = produceLetterPattern(pattern, 'A');
        return pattern;
    } ...
}

That's the general idea, you should be able to work it out from there. Important part is that you need a result returned, in the above example a String, returned via

return pattern;
bgse
  • 8,237
  • 2
  • 37
  • 39