使用循环输出 ASCII 菱形 [英] Output an ASCII diamond shape using loops

查看:45
本文介绍了使用循环输出 ASCII 菱形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a program in Java that captures an integer from the user (assume data is valid) and then outputs a diamond shape depending on the size of the integer, i.e. User enters 5, output would be:

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

到目前为止我有:

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 的值,但这只会产生菱形的左侧.

I was thinking about decreasing the value of h but that would only produce the left hand side of the diamond.

推荐答案

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 的评论我才意识到这是一个家庭作业.因此,我强烈建议您在将其用作最终版本之前了解此代码中的内容.有任何问题欢迎随时提问!

Ok, now this is the code, but as I saw S.L. Barth's comment I just realised this is a homework. So I strongly encourage you to understand what is written in this code before using it as final. Feel free to ask any questions!

这篇关于使用循环输出 ASCII 菱形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆