Java Scanner制作一个带星形的三角形(分为四个静态空格

时间:2016-12-07 14:08:54

标签: java java.util.scanner

我必须做这样的事情。

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

但我的老师要求以一些奇怪的格式必须遵循。并使用For循环语句。我需要输入的代码在(// Answer Here using For ... loop)下

import java.util.Scanner;
public class IsoTri3
{
    public static void main (String[] args) 
    {
        // declare viriable
        int height;
        Scanner sc = new Scanner(System.in);
        // Input height
        System.out.print("Enter the height of triangle: ");
        height = sc.nextInt();
        System.out.println(height);                 
        // Print triangle
        // Print Top
        topRow ( height );
        // Print Middle
        for (int j=2; j<= height-1; j++)
        {
            innerRow(j, height);
        }
        // Print Bottom
        lastRow( height );
    }
    //-------------------------------------------------------------------------//
    public static void topRow(int row)
    {
        //Answer Here using For...loop
    }

    public static void innerRow(int row,int h)
    {
        //Answer Here using For...loop
    }

    public static void lastRow(int h)
    {
        //Answer Here using For...loop
    }
}

1 个答案:

答案 0 :(得分:0)

你需要在这里找到一个模式。我们说高度为(2*n - 1)。所有行都有奇数5-1=4个星星。从第一行开始,它是这样的: 1星 3星 5星 7星 9星。你看到模式了吗?在每一行上,您必须打印 2个星星而不是前一行。忘记格式。首先,按照这种模式打印星星。

接下来是格式化。我假设最后一行在它前面有零空格。现在看看这里的模式。在第1行,您必须打印5-2=3个空格,第2行有5-3=2个空格,第3行有5-4=1个空格,第4行有5-5=0个空格,以及第5行(最后一行)有~/Development/DjangoDEV/FlowersVibeShoppe/venv-flowersvibe-oscar on master $ source bin/activate -bash: bin/activate: No such file or directory 个空格。

编码这不会非常棘手。