好的,我需要使用 for 循环制作一个金字塔,我需要用户输入三角形的底。我已经完成了大部分(我认为(,但我需要一些帮助,因为输出没有给出它的正确基础(底层(,它给出的比输入少两个 *......有人可以帮我解决这个问题吗?这是我到目前为止的代码:
import java.util.Scanner;
public class Client {
public static void pyramid(){
int x;
Scanner console = new Scanner(System.in);
System.out.println("What is the base?: ");
x = console.nextInt();
for (int i=1; i < x; i += 2){
for (int k=0; k < (4 - i / 2); k++){
System.out.print(" ");
}
for (int j=0; j< i ; j++){
System.out.print("*");
}
System.out.println("");
}
}
public static void main(String[] args) {
pyramid();
}
}
试试这个;
public static void pyramid() {
int x;
Scanner console = new Scanner(System.in);
System.out.println("What is the base?: ");
x = console.nextInt();
for (int i = 1; i <= x; i=i+2) {
int spaceCount = (x - i)/2; // how many space I will put for 5 firstly 2 spaces, then 1 space
for(int j = 0; j< x; j++) {
if(j < spaceCount || j >= (x - spaceCount)) {
System.out.print(" "); // put spaces before *
} else {
System.out.print("*");
}
}
System.out.println();
}
}
输出为 5;
What is the base?:
5
*
***
*****