我试图创建一个完整的钻石,我几乎全部钻石了
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));
}
这些for循环是创造钻石的原因,但spaces.substring是我遇到困难的地方。有人知道如何通过单独编辑spaces.substring来解决这个问题吗?
H
O O
U U
S S
E E
S S
U U
O O
H
正如您所看到的,每个for循环中的前两行创建了钻石的右半部分,最后一行创建了左半部分。但是左半部分没有spaces.substring,因为我不知道我会把它放进去。
应该是这样的:
awsProperties.getAccessKey()
答案 0 :(得分:0)
你被允许使用方法吗?
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