用Java怎么写金字塔
时间: 2023-05-19 11:02:19 浏览: 50
您可以使用以下Java代码来打印金字塔:
```
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = sc.nextInt();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
```
您可以输入行数,然后运行该程序,它将打印出一个金字塔形状。
相关问题
用Java写数字金字塔
以下是用 Java 写数字金字塔的代码:
```
import java.util.Scanner;
public class NumberPyramid {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入数字金字塔的行数:");
int rows = input.nextInt();
int number = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print(number + " ");
number++;
}
System.out.println();
}
}
}
```
希望能够帮到你!
使用Java script写金字塔
使用Javascript写金字塔可以通过循环嵌套语句来实现。以下是一个例子:
```
let rows = 5;
let output = "";
for(let i = 1; i <= rows; i++){
for(let j = 1; j <= i; j++){
output += "* ";
}
output += "\n";
}
console.log(output);
```
这段代码会输出一个由星号组成的金字塔,共有5行。你可以根据需要调整`rows`的值来改变金字塔的高度。