一题学会Java入门语法
题目:
提示用户从控制台输出1-15之间的任意数字n,然后输出n行数字金字塔。
例如:
Please Enter an integer between 1 and 15:6
Printing the number pyramid…
12 1 23 2 1 2 34 3 2 1 2 3 45 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
Java语法
-
for, while, if 用法同 c & c++
-
输出:
System.out.print("");
-
输出并换行:
System.out.println();
-
包声明:
package homework1;
- 作用:将类归入包
homework1
中,便于管理和组织代码。 - 与C++的区别:C++没有包的概念,而是使用命名空间(namespace)来组织代码。
- 作用:将类归入包
-
导入库:
import java.util.Scanner;
-
作用:导入
Scanner
类,用于从标准输入读取数据。 -
与C++的区别:C++通过包含头文件(如
<iostream>
)来使用输入输出功能,而Java使用import
语句导入所需的类。
-
-
类定义
public class Homework2_23 {public static void main(String[] args) {// 代码内容 } }
- 作用: 定义一个名为
Homework2_23
的公共类,并包含一个main
方法,这是Java程序的入口点。 - 与C++的区别: C++程序通常只有一个全局的
main
函数,而Java要求所有代码都必须位于类中。
- 作用: 定义一个名为
-
创建Scanner对象:
Scanner scanner = new Scanner(System.in);
- 作用:创建一个
Scanner
对象,用于读取标准输入(键盘输入)。 - 与C++的区别:在C++中,使用
std::cin
来读取输入,无需显式创建对象。
- 作用:创建一个
-
**输出提示信息: **
System.out.print(" ");
-
读取用户输入:
int n = scanner.nextInt();
-
作用:从标准输入读取一个整数,并赋值给变量
n
。 -
与C++的区别:C++使用
std::cin >> n;
来读取输入。
-
-
计算最大宽度:
int max_width = 2 * n - 1;
- 作用:计算金字塔的最大宽度,即当行数为n时的总宽度。
- 与C++的区别:两者语法相同,只是Java要求变量必须显式声明类型。
-
打印前导空格
for (int j = 0; j < (max_width - (2 * i - 1)) / 2; j++) { System.out.print(" "); }
其余部分基本同C++。
全部代码:
package homework1;
import java.util.Scanner;
public class Homework2_23
{public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("Please Enter an integer between 1 and 15: ");int n = scanner.nextInt();System.out.println("Printing the number pyramid...");int max_width = 2 * n - 1;for (int i = 1; i <= n; i++) {//n行// 打印前导空格 前导空格越来越少for (int j = 0; j < (max_width - (2 * i - 1)) / 2; j++) {System.out.print(" ");//没有数字, 一次两格}// 打印左边for (int k = i; k >= 1; k--) {System.out.print(k + " ");}// 打印右边for (int k = 2; k <= i; k++) {System.out.print(k + " ");}System.out.println();}}
}
C++版代码 (可对照学习) :
#include <iostream>
#include <string>using namespace std;int main() {int n;cout << "Please Enter an integer between 1 and 15: ";cin >> n;cout << "Printing the number pyramid..." << endl;int max_width = 2 * n - 1;for (int i = 1; i <= n; ++i) {// 打印前导空格for (int j = 0; j < (max_width - (2 * i - 1)) / 2; ++j) {cout << " ";}// 打印左边部分for (int k = i; k >= 1; --k) {cout << k << " ";}// 打印右边部分for (int k = 2; k <= i; ++k) {cout << k << " ";}cout << endl;}return 0;
}