gpt4 book ai didi

java - 带数字的空菱形

转载 作者:行者123 更新时间:2023-11-30 06:39:25 25 4
gpt4 key购买 nike

所以我被问到这个问题,我只能解决代码的顶部部分,我被困在底部部分。

Write a Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines as shown below. Sample output where n = 3:

  1
2 2
3 3
2 2
1

这是我到目前为止的代码:

public static void shape(int n) {
//TOP PART
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= 2 * i - n + 1; j++) {
System.out.print(" ");
}
System.out.println(i);
}

//BOTTOM PART (The messed up part)
for (int i = n + 1; i <= 2 * n - 2; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= n; j++) {
System.out.print(" ");
}
System.out.print(i);
}
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
}
public static void main(String[] args) {
shape(4);
}

最佳答案

也许有点晚了,但因为消息的底部部分只是镜像的第一部分,您可以使用 Stack 以相反的顺序打印消息:

public static void main(String[] args) {
int maxNumber = 3;
Stack<String> message = new Stack<>();
// upper part
for (int row = 0; row < maxNumber; row++) {
int prefix = maxNumber - (row + 1);
int spaces = row >= 2 ? row * 2 - 1 : row;

String line = getLine(row, prefix, spaces);
System.out.println(line);
if (row != maxNumber - 1)
message.add(line);
}
// bottom part
while (!message.isEmpty())
System.out.println(message.pop());
}

public static String getLine(int row, int prefix, int spaces) {
StringBuilder line = new StringBuilder("_".repeat(prefix));
line.append(row + 1);
if (row != 0) {
line.append("_".repeat(spaces));
line.append(row + 1);
}
return line.toString();
}

输出:

__1
_2_2
3___3
_2_2
__1

您当然可以使用任何您想要填充堆栈的方法(即生成消息的上部部分),就像这个问题建议的方法一样。我描述的上半部分包含第一行(包括)到中间行(不包括)。

关于java - 带数字的空菱形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44641520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com