在Java中将*打印为三角形? [英] Printing *s as triangles in Java?

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

问题描述

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

My assignment in my Java course is to make 3 triangles. One left aligned, one right aligned, and one centered. I have to make a menu for what type of triangle and then input how many rows is wanted. The triangles have to look like this

*
**
***
****


   *
  **
 ***
****


  *
 ***
*****

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

So far I was able to do the left aligned triangle but I can't seem to get the other two. I tried googling but nothing turned up. Can anyone help? I have this so far.

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

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


推荐答案

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

Hint: For each row, you need to first print some spaces and then print some stars. The number of spaces should decrease by one per row, while the number of stars should increase.

对于居中输出,增加星数<每行em>两个。

For the centered output, increase the number of stars by two for each row.

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

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