简体   繁体   English

用Java打印三角形

[英]Printing a triangle in Java

I'm practicing basic coding exercises and trying to print the following triangle in Java: 我正在练习基本的编码练习并尝试在Java中打印以下三角形:

*
***
*****
***
*

The following code gives me the results but I feel like there must be a much more elegant solution 以下代码给出了结果,但我觉得必须有一个更优雅的解决方案

    for (int i = 1; i <= 5; i++) {
        if (i % 2 == 1) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println("");
        }

    }
    for (int i = 3; i > 0; i--) {
        if (i % 2 == 1) {
        for (int j = 1; j < i + 1; j++) {
            System.out.print("*");
        }
        System.out.println("");
        }
    } 

Can anyone provide some insight into how to make this work in a better way? 任何人都可以提供一些有关如何以更好的方式使这项工作的见解?

Ok, here's some more code that produces the correct result that uses just the two for loops, but it looks even uglier: 好的,这里有一些代码可以生成只使用两个for循环的正确结果,但它看起来更加丑陋:

    for (int i = 1; i <= 10; i += 2) {
        if (i <= 5) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println("");

        }
        else if(i > 5 && i < 8){
            for(int j = i/2; j > 0; j--){
                System.out.print("*");
            }
            System.out.println("");
        }
        else{
            for(int j = 1; j > 0; j--){
                System.out.print("*");
            }
            System.out.println("");
        }
    }

First, you are skipping each 2nd iteration of the loop because you want to increase two steps at once. 首先,您正在跳过循环的每个第二次迭代,因为您希望一次增加两个步骤。 You can do this by changing the "i++" in your loop to "i += 2" and "i--" to "i -= 2", that will have the same effect and allows you to remove the if inside both loops. 您可以通过将循环中的“i ++”更改为“i + = 2”并将“i--”更改为“i - = 2”来实现此目的,这将具有相同的效果并允许您删除两个循环中的if 。

Another improvement would be using a single outer loop and figuring out whether the inner loop should be increasing or decreasing the amount of asterisks. 另一个改进是使用单个外环并确定内环是应该增加还是减少星号的数量。 Maybe you can come up with an equation that gives you the amount of asterisks based on the value of i? 也许你可以想出一个方程式,根据i的值给出你的星号数量? (I didn't want to solve it completely so you have some exercise left, just comment if you want a full solution) (我不想完全解决它,所以你还有一些练习,如果你想要一个完整的解决方案,请发表评论)

Updated with a solution that might be considered elegant as you can change the height of the triangle and there is no repetition: 更新了一个可能被认为是优雅的解决方案,因为您可以更改三角形的高度,并且没有重复:

int height = 5;
for (int i = 1; i <= 2 * height; i += 2) {
    int numAsterisks;
    if (i <= height) {
        numAsterisks = i;
    } else {
        numAsterisks = 2 * height - i;
    }

    for (int j = 0; j < numAsterisks; j++) {
        System.out.print("*");
    }
    System.out.println();
}

What about the following? 以下怎么样?

public void printTriangle(int size) {
    int half = size / 2;
    for (int i = 0; i < size; i++) {
        int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
        char[] a = new char[stars];
        Arrays.fill(a, '*');
        System.out.println(new String(a));
    }
}

Or just a bit more optimized: 或者只是稍微优化一下:

public void printTriangle(int size) {
    int half = size / 2;
    char[] a = new char[size];
    Arrays.fill(a, '*');
    for (int i = 0; i < size; i++) {
        int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
        System.out.println(new String(a, 0, stars));
    }
}
for(int i = 0; i < 7; i++) {
    for(int j = 0; j < i; j++) {
        print("*");
    }
    print("\n");
}

This can be another solution to print a regular right triangle... 这可以是打印常规直角三角形的另一种解决方案......

Here's a different way of looking at the problem. 这是查看问题的另一种方式。 By using an integer array, I can solve lots of shape drawing problems by changing the values in the array. 通过使用整数数组,我可以通过更改数组中的值来解决许多形状绘制问题。

When solving more difficult problems, you would use model classes instead of simple integers. 解决更难的问题时,可以使用模型类而不是简单的整数。 The idea, however, is the same. 然而,这个想法是一样的。

Here's the output. 这是输出。

*
***
*****
***
*

And here's the code: 这是代码:

public class Triangle {

    public static void main(String[] args) {
        int[] heights = {1, 3, 5, 3, 1};

        for (int i = 0; i < heights.length; i++) {
            for (int j = 0; j < heights[i]; j++) {
                System.out.print("*");
            }
            System.out.println("");
        }
    }

}

How about... 怎么样...

int width = 5;
for (int i = 1; i <= width; i+=2){
    System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
for (int i = width-2; i > 0; i-=2){
    System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}

Or, even better yet... 或者,甚至更好......

int width = 7;
double half = width / 2
for (int i = 0; i < width; i++){
    System.out.println(String.format("%"+((i < half ? i : (width-i-1))*2+1)+"s", "").replaceAll(" ", "*"));
}

Gives

*
***
*****
***
*

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

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