Write a program that reads a string and then prints a diamond shaped array based on the characters of the string. As an example, if the string has the value “SAMPLE”, then the program should print the pattern: S SAS SAMAS SAMPMAS SAMPLPMAS SAMPLELPMAS SAMPLPMAS SAMPMAS SAMAS SAS S The program should work for a string up to ten characters long. If a user supplies a string that is longer than ten characters, the program should use only the first ten characters in forming the pattern.
I need to the characters from the string to form a diamond shape (the shape is a little off above) and I think this may involve an approach with nested for loops, but not so sure how to get the program to take the first 10 and return it that way (ex; taking into account the spacing and everything
Deal with it as two separate problems, which they are. One function to return the munged string, and another to deal with positioning that string.
This is a fun project -- opens the way to cool designs;
some art;
Anyway-- I approached the problem by first observing the format of: ``` S SAS SAMAS SAMPMAS SAMPLPMAS SAMPLELPMAS SAMPLPMAS SAMPMAS SAMAS SAS S ``` I then divided the program into 2 main strings arrays -- the forwards portion, and the backwards portion -- (observe the backwards portion doesn't play a role in the first or last lines), using for loops and the String class's substring method, you should be able to get the 2 forward/backward arrays-- ie; ``` forwards[4]; //this holds the string "SAMPL"; ```
``` backwards[4]; //this holds the string "PMAS" ``` then, you can concatenate the forwards / backwards arrays in a for loop into a new string array called finalDisplay -- (you can use the String class's concat method) ie; ``` String str1 = "Hello"; String str2 = " World"; String show = str1.concat(str2); System.out.print(show); //prints "hello world" ``` As for the actual printing into a diamond format -- I used the StringBuilder class -- and made a StringBuilder array holding the same values as the String array finalDisplay -- In my spacing algorithm -- the number of lines away from the center the line is, is the number of spaces you add before it -- I do this using the StringBuilder class's insert method-- ie; ``` StringBuilder sb = new StringBuilder("Hello"); for(int i = 0; i < 10; i++) sb.insert(0, " "); System.out.print(sb.toString()); //prints out 10 spaces before Hello ``` Note the toString() method is needed to turn a StringBuilder into a String.
Join our real-time social learning platform and learn together with your friends!