首页 > 解决方案 > Java,需要帮助制作一个for循环来制作像带有单个字母的楼梯的图像

问题描述

我需要帮助来制作可以接受数字并打印该行数以制作图像的程序,并且它会像这样使用字母来表示图像。例如,我将输入数字 5,然后程序将打印这个.....

x
xx
xxx
xxxx
xxxxx 

|

public class Stairs
{
    public static void Stairs1 (int height)
    {
        for (int row = 0; row < height; row = row + 1) 
        {
            for (int col = 0; col <= row; col = col + 1) 
            {
                System.out.print("x");
            }
            System.out.println();
        }
    }
}

这是为了做到这一点。我正在尝试使事情变得更简单,但它会像这样从左侧翻转到右侧
......

    x
   xx
  xxx
 xxxx
xxxxx 

标签: javafor-loop

解决方案


试试下面的东西;它应该为您提供所需的输出:

// Function to demonstrate printing pattern 
    public static void printStars(int n) 
    { 
        int i, j; 

        // outer loop to handle number of rows 
        //  n in this case 
        for(i=0; i<n; i++) 
        { 

            // inner loop to handle number spaces 
            // values changing acc. to requirement 
            for(j=2*(n-i); j>=0; j--) 
            { 
                // printing spaces 
                System.out.print(" "); 
            } 

            //  inner loop to handle number of columns 
            //  values changing acc. to outer loop 
            for(j=0; j<=i; j++) 
            { 
                // printing stars 
                System.out.print("* "); 
            } 

            // ending line after each row 
            System.out.println(); 
        } 
    } 

    // Driver Function 
    public static void main(String args[]) 
    { 
        int n = 5; 
        printStars(n); 
    } 
} 

推荐阅读