I'm trying to create a full diamond and I have almost all of it down
T T
Te Te
Tes Tes
Test Test
Test Tes
Tes Te
Te T
T
These for loops are what create the diamonds, but the spaces.substring is where I am having difficulties. Would anyone know how to approach this by solely editing the spaces.substring?
for (int i = 0 ; i < len; i++)
{
System.out.print(SPACES.substring(0,i));
System.out.print (word.substring (0,i) + System.lineSeparator());
//System.out.print(SPACES.substring(i,i+1));
System.out.print (word.substring (0,i+1));
}
for (int g = len ; g >= 0; g--)
{
System.out.print(SPACES.substring(0,g));
System.out.print (word.substring (0,g) + System.lineSeparator());
System.out.print (word.substring (0,g));
}
As you can see the first two lines in each for loop create the right half of the diamond, and the last lines creates the left half. But there is no spaces.substring for the left half, because I don't know what I would put in it.
Should look like this:
H
O O
U U
S S
E E
S S
U U
O O
H
Are you allowed to use methods?
public static void main(String[] args)
{
new Main().printDiamond("HOUSE");
}
private void printDiamond(String word)
{
for (int i = 0 ; i < word.length(); i++)
{
printPart(word, i);
}
for (int i = word.length() - 2; i >= 0; i--)
{
printPart(word, i);
}
}
private void printPart(String word, int i)
{
space(word.length() - (i + 1));
System.out.print(word.charAt(i));
if (i > 0)
{
space((i * 2) - 1);
System.out.print(word.charAt(i));
}
space(word.length() - (i + 1));
System.out.println();
}
private void space(int i)
{
for (int j = 0; j < i; j++)
{
System.out.print(" ");
}
}
String word = "HOUSE";
String SPACES = " ";
int len = word.length();
for (int i = 0 ; i < len; i++)
{
System.out.print(SPACES.substring(0, len - (i + 1))); //print left padding spaces
System.out.print(word.charAt(i)); //print left/middle character
if (i > 0) //we don't want to do this on run 0 because there we only need to print one character in the middle (H)
{
System.out.print(SPACES.substring(0, (i * 2) - 1)); //print middle padding spaces
System.out.print(word.charAt(i)); //print right character
}
System.out.println(SPACES.substring(0, len - (i + 1))); //optional: print right padding
}
for (int i = len - 2; i >= 0; i--) //start at len - 2. -1 because arrays start at 0 and -1 because we don't want to print the last character (E) again
{
System.out.print(SPACES.substring(0, len - (i + 1)));
System.out.print(word.charAt(i));
if (i > 0)
{
System.out.print(SPACES.substring(0, (i * 2) - 1));
System.out.print(word.charAt(i));
}
System.out.println(SPACES.substring(0, len - (i + 1)));
}
H
O O
U U
S S
E E
S S
U U
O O
H