如何在java中打印数字三角形 [英] how to print a number triangle in java

查看:3220
本文介绍了如何在java中打印数字三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成如图所示的三角形:

I need to produce a triangle as shown:

    1
   22
  333
 4444
55555

我的代码是:

int i, j;
for(i = 1; i <= 5; i++)
{
    for(j = 1; j <= i; j++)  
    {          
        System.out.print(i); 
    }      
    System.out.print("\n");        
}

以相反的方式生成三角形

Producing a triangle the opposite way

1
22
333
4444
55555

我需要对我的代码做什么才能使其面向正确的方式?

What do i need to do to my code to make it face the right way?

推荐答案

你需要3个for循环:

You need 3 for loops:


  1. 要重复和打印的实际数字的上级循环

  2. 打印空格的第一个内部级别

  3. 重复打印数字的第二个内部级别

  4. 结束时上层循环打印新行

  1. Upper-level loop for the actual number to be repeated and printed
  2. first inner level for printing the spaces
  3. second inner level for to print the number repeatedly
  4. at the end of the Upper-level loop print new line

代码:

public void printReversedTriangle(int num)
{
    for(int i=0; i<=num; i++)
    {
        for(int j=num-i; j>0; j--)
        {
            System.out.print(" ");
        }
        for(int z=0; z<i; z++)
        {
            System.out.print(i);
        }
        System.out.println();
    }
}

输出:

     1
    22
   333
  4444
 55555
666666

这篇关于如何在java中打印数字三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆