gpt4 book ai didi

java - 使用循环输出 ASCII 菱形

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:24:29 31 4
gpt4 key购买 nike

我正在尝试用 Java 编写一个程序,从用户那里捕获一个整数(假设数据有效),然后根据整数的大小输出一个菱形,即用户输入 5 ,输出将是:

--*--
-*-*-
*---*
-*-*-
--*--

到目前为止我有:

if (sqr < 0) {
// Negative
System.out.print("#Sides of square must be positive");
}
if (sqr % 2 == 0) {
// Even
System.out.print("#Size (" + sqr + ") invalid must be odd");
} else {
// Odd
h = (sqr - 1) / 2; // Calculates the halfway point of the square
// System.out.println();
for (j = 0; j < sqr; j++) {
for (i = 0; i < sqr; i++) {
if (i != h) {
System.out.print(x);
} else {
System.out.print(y);
}
}
System.out.println();
}
}

这只是输出:

--*--
--*--
--*--
--*--
--*--

我正在考虑降低 h 的值,但这只会产生钻石的左侧。

最佳答案

void Draw(int sqr) {
int half = sqr / 2;
for (int row = 0; row < sqr; row++) {
for (int column = 0; column < sqr; column++) {
if ((column == Math.abs(row - half))
|| (column == (row + half))
|| (column == (sqr - row + half - 1))) {
System.out.print("*");
} else {
System.out.print("_");
}
}
System.out.println();
}
}

好的,现在这是代码,但正如我看到的 S.L. Barth 的评论我才意识到这是一个家庭作业。因此,我强烈建议您在将其用作最终版本之前了解此代码中编写的内容。欢迎提出任何问题!

关于java - 使用循环输出 ASCII 菱形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7887681/

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