21xrx.com
2025-03-21 08:27:15 Friday
文章检索 我的文章 写文章
如何编写Java数字金字塔代码
2023-06-18 14:10:34 深夜i     34     0
Java 数字金字塔 循环语句

在Java编程中,数字金字塔是一种常见的练习题,用于提升学生的循环和条件语句处理能力。数字金字塔代码需要使用嵌套循环和条件语句,按照预定的规则输出数字金字塔。

为了编写Java数字金字塔代码,我们需要定义变量来存储金字塔的行数,然后使用嵌套循环来创建数字金字塔。在内部循环中,我们需要使用if语句来确定当前循环是奇数行还是偶数行,并针对性地进行计算输出。

以下是一个简单的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();
    for (int i = 1; i <= rows; i++) {
      for (int j = 1; j <= i; j++) {
        if (i % 2 != 0) {
          System.out.print(j + " ");
        } else {
          System.out.print(i - j + 1 + " ");
        }
      }
      System.out.println();
    }
  }
}

通过输入行数,运行上述代码将会输出一个相应行数的数字金字塔。

  
  

评论区