java - 如何打印两个前端相接触的三角形?

标签 java for-loop

我正在尝试制作一个看起来像这样的三角形

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

我有执行此操作的代码,但我不确定我的方法是否是完成此操作的正确方法,因为我无法使用小于 4 的值作为我的 n 参数。

 public static void triangle(int n){   
    int shift = n*2 + 2;

    for(int row = 0; row <= n; row++ ){
        for(int j = 0; j <= (n*2)+(n/2); j++ ){
            if(j == 0 || j==shift){
                for(int i = 0; i <= row; i++){ 
                    System.out.print("*");
                    if(row == n && i == n)
                        System.out.print("*");

                }
            }

            if(row != n)
                System.out.print(' ');

        }
        shift-=2;
        System.out.println();
    }
}  

最佳答案

这是解决方案。

public static void triangle(int n){ 
    int shift = n*2;
    for(int row = 1; row <= n; row++ ){
        for(int j = 0; j < row; j++ )
            System.out.print("*");
        shift-=2;
        for(int k = 0 ; k<shift; k++)
            System.out.print(" ");

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


    }

关于java - 如何打印两个前端相接触的三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28868866/

相关文章:

JavaScript 函数并不执行所有内容

javascript - 如何使用 lodash _.filter 与 _.forEach 重构 for 循环?

java - android.support.v7.widget.Toolbar 在棉花糖设备上无法正常工作

Java JDBC-ODBC 无法加载 Excel 驱动程序

java - 检索给定 objectId 的 ParseObject 的 ACL

java - 带数组的 For 语句

java - 使用 MouseWheelListener 水平滚动

java - Spring 批处理 : Skip a record that cannot be written to the database and proceed with the next record

javascript - 为什么在 Javascript 中使用 for in 循环会出现这种情况?

c++ - 将 R 代码转换为 C++ 以进行 Rcpp 实现