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

前端之家收集整理的这篇文章主要介绍了在Java中将*打印为三角形?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在 Java课程中的任务是制作3个三角形.一个左对齐,一个右对齐,一个居中.我必须为什么类型的三角形创建一个菜单,然后输入需要多少行.三角形必须看起来像这样
  1. *
  2. **
  3. ***
  4. ****
  5.  
  6.  
  7. *
  8. **
  9. ***
  10. ****
  11.  
  12.  
  13. *
  14. ***
  15. *****

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

  1. import java.util.*;
  2. public class Prog673A
  3. {
  4. public static void leftTriangle()
  5. {
  6. Scanner input = new Scanner (System.in);
  7. System.out.print("How many rows: ");
  8. int rows = input.nextInt();
  9. for (int x = 1; x <= rows; x++)
  10. {
  11. for (int i = 1; i <= x; i++)
  12. {
  13. System.out.print("*");
  14. }
  15. System.out.println("");
  16. }
  17. }
  18. public static void rightTriangle()
  19. {
  20. Scanner input = new Scanner (System.in);
  21. System.out.print("How many rows: ");
  22. int rows = input.nextInt();
  23. for (int x = 1; x <= rows; x++)
  24. {
  25. for (int i = 1; i >= x; i--)
  26. {
  27. System.out.print(" ");
  28. }
  29. System.out.println("*");
  30. }
  31. }
  32. public static void centerTriangle()
  33. {
  34.  
  35. }
  36. public static void main (String args [])
  37. {
  38. Scanner input = new Scanner (System.in);
  39. System.out.println("Types of Triangles");
  40. System.out.println("\t1. Left");
  41. System.out.println("\t2. Right");
  42. System.out.println("\t3. Center");
  43. System.out.print("Enter a number: ");
  44. int menu = input.nextInt();
  45. if (menu == 1)
  46. leftTriangle();
  47. if (menu == 2)
  48. rightTriangle();
  49. if (menu == 3)
  50. centerTriangle();
  51. }
  52. }

样本输出

  1. Types of Triangles
  2. 1. Left
  3. 2. Right
  4. 3. Center
  5. Enter a number (1-3): 3
  6. How many rows?: 6
  7.  
  8. *
  9. ***
  10. *****
  11. *******
  12. *********
  13. ***********

解决方法

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

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

猜你在找的Java相关文章