原文: https://beginnersbook.com/2014/04/java-program-to-print-floyds-triangle-example/

示例程序:

该程序将提示用户输入行数,并根据输入,打印具有相同行数的 Floyd 三角形

  1. /* Program: It Prints Floyd's triangle based on user inputs
  2. * Written by: Chaitanya from beginnersbook.com
  3. * Input: Number of rows
  4. * 输出: floyd's triangle*/
  5. import java.util.Scanner;
  6. class FloydTriangleExample
  7. {
  8. public static void main(String args[])
  9. {
  10. int rows, number = 1, counter, j;
  11. //To get the user's input
  12. Scanner input = new Scanner(System.in);
  13. System.out.println("Enter the number of rows for floyd's triangle:");
  14. //Copying user input into an integer variable named rows
  15. rows = input.nextInt();
  16. System.out.println("Floyd's triangle");
  17. System.out.println("****************");
  18. for ( counter = 1 ; counter <= rows ; counter++ )
  19. {
  20. for ( j = 1 ; j <= counter ; j++ )
  21. {
  22. System.out.print(number+" ");
  23. //Incrementing the number value
  24. number++;
  25. }
  26. //For new line
  27. System.out.println();
  28. }
  29. }
  30. }

输出:

  1. Enter the number of rows for floyd's triangle:
  2. 6
  3. Floyd's triangle
  4. ****************
  5. 1
  6. 2 3
  7. 4 5 6
  8. 7 8 9 10
  9. 11 12 13 14 15
  10. 16 17 18 19 20 21