在java中创建一个颠倒的三角形

我试图让我已经弥补的三角形朝下。 尝试了很多次,但我不知道该怎么做。

我所知道的代码是:

public static void drawPyramide(int lines, char symbol, boolean startDown) { //TRIANGLE if(startDown) { //The triangle up side down should be here. } else { int c = 1; for (int i = 0; i < lines; i++) { for (int j = i; j < lines; j++) { System.out.print(" "); } for (int k = 1; k <= c; k++) { if (k%2==0) System.out.print(" "); else System.out.print(symbol); } System.out.print("\n"); c += 2; } } } 

有什么建议我可以“翻转”这个三角形吗? 谢谢。

要翻转三角形,您只需要改变迭代的方向。 而不是从i = 0i < lines你需要从i = lines-1下降到i >= 0

您还需要将c更改为要开始的空格和符号的数量。

看起来像这样:

 int c = 2*lines; for (int i = lines-1; i>=0; i--) { for (int j = i; j < lines; j++) { System.out.print(" "); } for (int k = 1; k <= c; k++) { if (k % 2 == 0) { System.out.print(" "); } else { System.out.print(symbol); } } System.out.print("\n"); c -= 2; } 

反转第一个循环条件,即从行数开始并减少它。 同时调整你的c ,使其从高到低降低,例如:

  int c = 2*lines-1; for (int i = lines; i > 0; i--) { for (int j = i; j < lines; j++) { System.out.print(" "); } for (int k = 1; k <= c; k++) { if (k%2==0) System.out.print(" "); else System.out.print(symbol); } System.out.print("\n"); c -= 2; } 
 import java.util.Scanner; public class EquilateralTraingle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int side = sc.nextInt(); constructEquTri(side); } private static void constructEquTri(int length) { // loop for each line for (int i = length; i > 0; i--) { // loop for initial spaces in each line for (int k = 0; k < length - i; k++) { System.out.print(" "); } // loop for printing * in each line for (int j = 0; j < i; j++) { System.out.print("*"); System.out.print(" "); } System.out.println(); } } } /*Output: 10 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */