欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > 一题学会Java入门语法(需C\C++基础)

一题学会Java入门语法(需C\C++基础)

2025/2/24 14:48:26 来源:https://blog.csdn.net/qq_42995393/article/details/145811492  浏览:    关键词:一题学会Java入门语法(需C\C++基础)

一题学会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语法

  1. for, while, if 用法同 c & c++

  2. 输出: System.out.print("");

  3. 输出并换行: System.out.println();

  4. 包声明: package homework1;

    1. 作用:将类归入包homework1中,便于管理和组织代码。
    2. 与C++的区别:C++没有包的概念,而是使用命名空间(namespace)来组织代码。
  5. 导入库: import java.util.Scanner;

    1. 作用:导入Scanner类,用于从标准输入读取数据。

    2. 与C++的区别:C++通过包含头文件(如<iostream>)来使用输入输出功能,而Java使用import语句导入所需的类。

  6. 类定义

    public class Homework2_23 
    {public static void main(String[] args) {// 代码内容 }
    }
    
    1. 作用: 定义一个名为Homework2_23的公共类,并包含一个main方法,这是Java程序的入口点。
    2. 与C++的区别: C++程序通常只有一个全局的main函数,而Java要求所有代码都必须位于类中。
  7. 创建Scanner对象: Scanner scanner = new Scanner(System.in);

    1. 作用:创建一个Scanner对象,用于读取标准输入(键盘输入)。
    2. 与C++的区别:在C++中,使用std::cin来读取输入,无需显式创建对象。
  8. **输出提示信息: **System.out.print(" ");

  9. 读取用户输入: int n = scanner.nextInt();

    1. 作用:从标准输入读取一个整数,并赋值给变量n

    2. 与C++的区别:C++使用std::cin >> n;来读取输入。

  10. 计算最大宽度: int max_width = 2 * n - 1;

    1. 作用:计算金字塔的最大宽度,即当行数为n时的总宽度。
    2. 与C++的区别:两者语法相同,只是Java要求变量必须显式声明类型。
  11. 打印前导空格

    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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词