微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Java中将*打印为三角形?

我在 Java课程中的任务是制作3个三角形.一个左对齐,一个右对齐,一个居中.我必须为什么类型的三角形创建一个菜单,然后输入需要多少行.三角形必须看起来像这样
*
**
***
****


   *
  **
 ***
****


  *
 ***
*****

到目前为止,我能够做左对齐的三角形,但我似乎无法得到另外两个.我试过谷歌搜索但没有出现.有人可以帮忙吗?到目前为止我有这个.

import java.util.*;
public class Prog673A
{
    public static void leftTriangle()
    {
        Scanner input = new Scanner (system.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i <= x; i++)
            {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
    public static void rightTriangle()
    {
        Scanner input = new Scanner (system.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i >= x; i--)
            {
                System.out.print(" ");
            }
            System.out.println("*");
        }
    }
    public static void centerTriangle()
    {

    }
    public static void main (String args [])
    {
        Scanner input = new Scanner (system.in);
        System.out.println("Types of Triangles");
        System.out.println("\t1. Left");
        System.out.println("\t2. Right");
        System.out.println("\t3. Center");
        System.out.print("Enter a number: ");
        int menu = input.nextInt();
        if (menu == 1)
            leftTriangle();
        if (menu == 2)
            rightTriangle();
        if (menu == 3)
            centerTriangle();
    }
}

样本输出

Types of Triangles
1.  Left
2.  Right
3.  Center
Enter a number (1-3):  3
How many rows?: 6

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

解决方法

提示:对于每一行,您需要首先打印一些空格,然后打印一些星星.
每行的空格数应减少一个,而星数应增加.

对于居中输出,每行增加星数2.

原文地址:https://www.jb51.cc/java/128228.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐