【问题标题】:Beginner in Java - Controlling output - Generating AsterixJava 初学者 - 控制输出 - 生成 Asterix
【发布时间】:2012-02-08 06:52:33
【问题描述】:

我在完成这个程序时遇到了困难。我正在尝试制作一个创建星号的程序,然后将其变成三角形。

这是我已经拥有的。

public class 12345 {
    public static void main(String[] args) {
        int n = 0;
        int spaces = n;
        int ast;

        System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");

        Scanner keyboard = new Scanner(System.in);
        n = keyboard.nextInt();

        for (int i = 0; i < n; i++) {
            ast = 2 * i + 1;

            for (int j = 1; j <= spaces + ast; j++) {
                if (j <= spaces)
                    System.out.print(' ');
                else
                    System.out.print('*');
            }

            System.out.println();
            spaces--;
        }
    }
}

它正在创建星号,但我如何才能在它们形成三角形的地方继续它们......所以它们会随着它们变大,然后变小......

提前感谢您!

【问题讨论】:

  • 允许以数字开头的类名?????
  • 你想做菱形的结构吗?
  • 从创建Right angled triangle开始。

标签: java whitespace drjava


【解决方案1】:

尝试移动

int spaces = n;

从标准输入读取n 的值之后。

这解决了你一半的问题,并希望让你走上正轨。

【讨论】:

  • 这只会解决一半的钻石(将打印顶部三角形)
  • 是的,但由于这可能是家庭作业,我只是想把他推向正确的方向。但你是对的;我将更新我的答案,使其更加明确。
  • 它已经打印出一半的三角形。我只是想教自己如何在创建整个三角形的地方制作它。
【解决方案2】:

我在您的代码中添加了一些内容并让它打印完整的三角形,其中扫描仪中输入的数字将是底行中打印的星号数。 IE。如果输入为 3,则三角形将为两行 1->3;如果输入为 5,则三角形将是 3 行 1->3->5,依此类推。

    public static void main(String[] args) {
        int ast;
        int reverse = 1;

        System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");

        Scanner keyboard = new Scanner(System.in);
        int spaces = keyboard.nextInt();


        for (int i = 0; i < spaces; i++) {
            ast = 2 * i + 1;

            for (int j = 1; j <= spaces + ast; j++) {
                if (j <= spaces) {
                    System.out.print(' ');
                } else {
                    System.out.print('*');}
                if (j > spaces + ast) {
                    for (int k = 0; k < spaces-(reverse-1); k++) {
                        System.out.print(' ');
                    }
                }
                int k = 0;
                reverse++;

            }

            System.out.println();
            spaces--;
        }
    }
}

我在 if-else 之后添加了另一个 if 语句,当变量 j 超过第一个循环条件时触发。这会触发另一个循环,通过基本上重复您的第一个 if 语句来使输出线对称。

我希望这会有所帮助 =)

【讨论】:

    猜你喜欢
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2019-05-04
    • 2015-02-12
    相关资源
    最近更新 更多