我应该编写一个嵌套的 for 循环来打印以下输出:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
我应该使用两种方法。
main 方法只应该从用户那里获取所需的行数。我应该编写另一个名为 printPyramid 的方法:
- 有行数
- 打印具有该行数的金字塔
- 什么都不返回。
到目前为止,我有:
import java.util.Scanner;
public class Pyramid {
//Getting number of rows, calling printPyramid in main method
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Get user input = number of lines to print in a pyramid
System.out.println("Enter the number of lines to produce: ");
int numLines = input.nextInt();
//call method:
printPyramid();
}//End of main method
//Making a new method...
public static void printPyramid (int numLines) {
int row;
int col;
row = 0;
col = 0;
for (row = 1; row <= numLines; row++){
//print out n-row # of spaces
for (col = 1; col <= numLines-row; col++){
System.out.print(" ");
}
//print out digits = 2*row-1 # of digits printed
for (int dig= 1; dig <= 2*row-1; dig++){
System.out.print(row + " ");
}
System.out.println();
}//end of main for loop
}//end of printPyramid
}//end of class
我得到错误,我不知道如何让它正确打印出来。我相信方法搞砸了?