I am trying to make a full triangle with any text input. Example if I have string that is "abcdefghij" I want the result to be
    aj
   abij
  abchij
 abcdghij
abcdefghij
if the string length is odd as in "abcdefghij" then the output would be
    a
   abi
  abchi
 abcdghi
abcdefghi
Here is what I have so far but my output for the words is upside down. My output is
    abcdefghij
   abcdghij
  abchij
 abij
aj
What I have done so far
public static void main(String[] args) {
        solve("abcdefghij");
    }
    public static void solve(String word) {
        solve(word, word.length()/2-1);
    }
    public static void solve(String word, int it) {
        // print starting spaces
        for(int i = 0; i < it; i++)
            System.out.print(" ");
        // print out string
        System.out.print(word+"\n");
        if(word.length() > 2) {
            int newlengthperside = (word.length() - 2)/2;
            solve( word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it-1);
        }
    }
I just need a suggestion on how to start from aj instead of the end. Thanks for any help. This is homework so just a hint is appreciated.
You code should look like this :
 public void solve(String str) {
    for(int i=1;i<=str.length()/2;i++) {
        for(int j=str.length()/2-i; j>0 ;j--) {
            System.out.print(" ");
        }
        System.out.print(str.substring(0,i));
        System.out.print(str.substring(str.length()-i));
        System.out.println();
    }
}
Input :
"abcdefghij"
Output:
    aj
   abij
  abchij
 abcdghij
abcdefghij
This only covers the happy path but you show understand the logic.
public static void solve(String word) {
    solve(word, 0);
}
public static void solve(String word, int it) {
    // print starting spaces
    String spaces="";
    for(int i = 0; i < it; i++)
        spaces+=" ";
    if(word.length() > 2) {
        int newlengthperside = (word.length() - 2)/2;
        solve(word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it + 1);
    }
    System.out.print(spaces+word+"\n");
}
I changed a few things: 
1. counting number of spaces needed and putting them in a string which is used later on.
String spaces="";
for(int i = 0; i < it; i++)
  spaces+=" ";
solve(word, 0); //-> 0 from length
solve(word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it + 1); //-> adding 1 to the length
Input :
solve("abcdefghij");
Output :
    aj
   abij
  abchij
 abcdghij
abcdefghij
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With