打印由星号组成的倒三角形 [英] Printing an upside down triangle made of asterisks

查看:1842
本文介绍了打印由星号组成的倒三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class upsidedown {

    public static void main(String args[]) {
        int x, y;
        for (y = 1; y <= 5; y++) {
            for (x = 0; x < 5 - y; x++) {
                System.out.print(' ');
            }
            for (x = (2 - y); x < (2 - y) + (2 * y - 1); x++) {
                System.out.print('*');
            }
            System.out.print('\n');
        }
    }
}

到目前为止我的代码打印出来了一个规则的右侧三角形。如何将其颠倒过来?

So far my code prints out a regular, right side up triangle. How do I make it upside down?

推荐答案

非常容易。使用相同的逻辑,只需颠倒打印行的顺序。

Very easily. Using your same logic, just reverse the order that you print your lines with.

public class UpsideDown {
    public static void main(String args[]) {
        int x, y;
        for (y = 5; y >= 1; y--) { //reverse here
            for (x = 0; x < 5 - y; x++)
                System.out.print(' ');
            for (x = (2 - y); x < (2 - y) + (2 * y - 1); x++)
                System.out.print('*');
            System.out.print('\n');
        }
   }
}

此外,请按照 java命名约定

这篇关于打印由星号组成的倒三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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