简体   繁体   English

如何创建给定图片中的三角形?

[英]How do I create the triangle as in the given picture?

Triangle [1]: https://i.stack.imgur.com/dTJkc.png三角形[1]: https://i.stack.imgur.com/dTJkc.png

I am not able to get the image with my code.我无法使用我的代码获取图像。 Help.帮助。

    for (int col=1; col<=size; col++) {
            if(col >=row || col==row)    {
            System.out.print(col );
        }else {
            System.out.print(" ");
        }
    }
    System.out.println();
}```

You can do it like this, and if you want a bigger or smaller triangle, adjust the value of the variable numberOfRows .你可以这样做,如果你想要一个更大或更小的三角形,调整变量numberOfRows的值。

    Integer numberOfRows = 8;

    for (int i = numberOfRows; i > 0; i--) {
        for (int k = 0; k < numberOfRows - i; k++) {
            System.out.print("  ");
        }
        for (int j = 1; j <= i; j++) {
            System.out.print(j + " ");
        }
        System.out.println();
    }

There are cleaner and better ways of doing this, but that should do the job.有更清洁和更好的方法可以做到这一点,但这应该可以完成工作。

  1. The first loop takes care of displaying the right amount of rows, iterating through numberOfRows .一个循环负责显示正确数量的行,遍历numberOfRows

  2. The second loop takes care of displaying spaces before each row, according to the image.根据图像,第二个循环负责在每一行之前显示空格。 Each row have an increasing amount of spaces before the row starts, so for the first one we have zero spaces before, for the second, we have one and so on.每行在行开始之前都有越来越多的空格,所以对于第一行,我们之前有零个空格,对于第二个,我们有一个,依此类推。 So the value that increases according to this logic as the i value change, is the difference between numberOfRows and the value i .因此,随着 i 值的变化,根据此逻辑增加的值是numberOfRows 与值 i之间的差值。

  3. The third loop takes care of displaying the right amount of numbers in each row.第三个循环负责在每一行中显示正确数量的数字。 The first row should have the same amount of numbers as the number of rows.第一行的数字应与行数相同。 So increasing the row number by one, we'll need to decrease the amount of numbers in the current row.因此,将行号增加一,我们需要减少当前行中的数字数量。

    int x = 8;
    int y = -1;
    for (int i = 1; i<=8; i++){
        for (int j = 0; j <=y; j++) {
            System.out.print("  ");

        }
        for (int j = 1; j <= x; j++) {
            System.out.print(j  + " ");
        }
        x--;
        y++;
        System.out.println();
    }

You can do it like this:你可以这样做:

for(int i = 1; i <= 8; i++){
    for(int j = 2; j <= 9; j++){
        int k = j - i;
        if(k > 0) System.out.print(k + " ");
        else System.out.print("  ");
    }
    System.out.println();
}

A bit shorter is that (with use of the Ternary Operator)更短一点的是(使用三元运算符)

for(int i = 1; i <= 8; i++){
    for(int j = 2; j <= 9; j++){
        int k = j - i;
        System.out.print(k > 0 ? k + " " : "  ");
    }
    System.out.println();
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM