Java学习笔记(一):常量、变量、输入输出

1. Java与C语言对比概述

特性C语言Java
编程范式面向过程面向对象
编译方式编译为机器码 编译为字节码(.class)在JVM上运行
内存管理手动管理(malloc/free)自动垃圾回收(GC)
跨平台性需针对不同平台重新编译“一次编写,到处运行”
指针支持指针操作 无指针使用引用
数组数组与指针关系密切 数组是对象有length属性

2. 第一个Java程序

2.1 Hello World 程序

// HelloWorld.java

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello, World!");

    }

}

2.2 编译与运行

# 编译

javac HelloWorld.java # 生成 HelloWorld.class



# 运行

java HelloWorld # 输出: Hello, World!# 编译

javac HelloWorld.java # 生成 HelloWorld.class



# 运行

java HelloWorld # 输出: Hello, World!

2.3 与C语言的对比

// C语言版本

#include <stdio.h>



int main() {

    printf("Hello, World!\n");

    return 0;

}
对比项C语言Java
文件命名任意名称.c类名必须与文件名相同
程序入口int main(void) 或 int main(int argc, char *argv[])public static void main(String[] args)
输出函数printf()System.out.println()
编译运行编译链接为可执行文件编译为字节码,JVM运行

3. 注释

// 单行注释



/*

 * 多行注释

 * 可以跨多行

 */



/**

 * 文档注释

 * 用于生成API文档

 * @author 作者

 * @version 版本

 */

public class Comments {

    public static void main(String[] args) {

        // 这是单行注释

        System.out.println("Hello");

        

        /*

         * 多行注释

         * 用于临时注释代码块

         */

    }

}

4. 常量

4.1 字面常量

public class Literals {

    public static void main(String[] args) {

        // 整型常量

        int decimal = 100; // 十进制

        int octal = 0144; // 八进制(0开头)

        int hex = 0x64; // 十六进制(0x开头)

        int binary = 0b1100100; // 二进制(0b开头,Java 7+)

        

        // 浮点型常量

        float f1 = 3.14f; // float后缀 f/F

        double d1 = 3.14; // double默认

        double d2 = 3.14d; // 可选后缀

        double scientific = 1.23e-4; // 科学计数法

        

        // 字符常量

        char c1 = 'A';

        char c2 = '\u0041'; // Unicode编码

        char c3 = '\n'; // 转义字符

        

        // 字符串常量

        String str = "Hello, Java";

        

        // 布尔常量

        boolean bool1 = true;

        boolean bool2 = false;

        

        // 空常量

        String nullStr = null;

        

        System.out.println("十进制: " + decimal);

        System.out.println("二进制: " + binary);

        System.out.println("浮点数: " + d1);

        System.out.println("字符: " + c1);

        System.out.println("字符串: " + str);

        System.out.println("布尔: " + bool1);

    }

}

4.2 命名常量(final)

public class Constants {

    // 类常量(全局常量)

    public static final double PI = 3.1415926535;

    public static final int MAX_USERS = 100;

    public static final String APP_NAME = "MyApplication";

    

    public static void main(String[] args) {

        // 局部常量

        final int LOCAL_MAX = 50;

        

        // PI = 3.14; // 错误!final常量不能重新赋值

        

        System.out.println("PI = " + PI);

        System.out.println("最大用户数 = " + MAX_USERS);

        System.out.println("应用名称 = " + APP_NAME);

        System.out.println("局部常量 = " + LOCAL_MAX);

    }

}

4.3 与C语言的对比

// C语言常量

#define PI 3.14159 // 宏常量(预处理)

const double PI = 3.14159; // const常量

对比项C语言Java
常量定义#define 或 constfinal 关键字
宏常量支持不支持
命名习惯全大写全大写(习惯)

5. 变量

5.1 基本数据类型

public class Variables {

    public static void main(String[] args) {

        // 1. 整型

        byte b = 127; // 1字节,范围:-128~127

        short s = 32767; // 2字节,范围:-32768~32767

        int i = 2147483647; // 4字节,范围:-2^31~2^31-1

        long l = 9223372036854775807L; // 8字节,需要L后缀

        

        // 2. 浮点型

        float f = 3.14159f; // 4字节,需要f后缀

        double d = 3.1415926535; // 8字节,默认

        

        // 3. 字符型

        char c = 'A'; // 2字节,Unicode编码

        

        // 4. 布尔型

        boolean bool = true; // 只有true和false,不能与整数互换

        

        System.out.println("byte: " + b);

        System.out.println("short: " + s);

        System.out.println("int: " + i);

        System.out.println("long: " + l);

        System.out.println("float: " + f);

        System.out.println("double: " + d);

        System.out.println("char: " + c);

        System.out.println("boolean: " + bool);

    }

}

5.2 类型转换

public class TypeConversion {

    public static void main(String[] args) {

        // 自动类型转换(隐式转换)- 小范围转大范围

        byte b = 100;

        int i = b; // byte → int

        long l = i; // int → long

        float f = l; // long → float

        double d = f; // float → double

        

        System.out.println("自动转换: byte(" + b + ") → int(" + i + ")");

        

        // 强制类型转换(显式转换)- 大范围转小范围可能丢失精度

        double pi = 3.14159;

        int intPi = (int) pi; // 截断小数部分

        byte byteValue = (byte) 200; // 溢出,200 → -56

        

        System.out.println("double 3.14159 → int: " + intPi);

        System.out.println("int 200 → byte: " + byteValue);

        

        // 字符串转数字

        String numStr = "123";

        int num = Integer.parseInt(numStr);

        double dnum = Double.parseDouble("3.14");

        

        // 数字转字符串

        String str1 = Integer.toString(456);

        String str2 = String.valueOf(789);

        

        System.out.println("字符串转数字: " + num);

        System.out.println("数字转字符串: " + str1);

    }

}

5.3 与C语言的对比

对比项C语言Java
char类型1字节,ASCII2字节,Unicode
boolean类型0/1 或 _Bool独立类型,只有true/false
long类型通常4或8字节固定8字节
类型大小平台相关平台无关(JVM规范)
自动转换允许隐式转换小范围转大范围自动,反之需强制
字符串字符数组 char[]String类(对象)

6. 输入输出

6.1 输出

import java.io.*;



public class OutputDemo {

    public static void main(String[] args) {

        // 基本输出

        System.out.print("不换行输出");

        System.out.println("换行输出");

        

        // 格式化输出

        int age = 25;

        String name = "张三";

        double score = 92.5;

        

        System.out.printf("姓名:%s,年龄:%d,成绩:%.1f\n", name, age, score);

        System.out.format("姓名:%s,年龄:%d,成绩:%.1f\n", name, age, score);

        

        // 常用格式说明符

        // %d - 整数

        // %f - 浮点数

        // %s - 字符串

        // %c - 字符

        // %b - 布尔

        // %x - 十六进制

        // %n - 换行符

        

        System.out.printf("十进制:%d,十六进制:%x,八进制:%o\n", 100, 100, 100);

        System.out.printf("浮点数:%.2f,科学计数:%e\n", 3.14159, 3.14159);

        System.out.printf("字符串:%10s(右对齐),%-10s(左对齐)\n", "Java", "Java");

        

        // 错误输出

        System.err.println("这是错误信息");

    }

}

6.2 输入 - Scanner类

import java.util.Scanner;



public class InputDemo {

    public static void main(String[] args) {

        // 创建Scanner对象

        Scanner scanner = new Scanner(System.in);

        

        System.out.println("===== 请输入个人信息 =====");

        

        // 读取字符串

        System.out.print("姓名:");

        String name = scanner.nextLine();

        

        // 读取整数

        System.out.print("年龄:");

        int age = scanner.nextInt();

        

        // 读取浮点数

        System.out.print("身高(米):");

        double height = scanner.nextDouble();

        

        // 读取布尔值

        System.out.print("是否学生(true/false):");

        boolean isStudent = scanner.nextBoolean();

        

        // 注意:nextInt()、nextDouble()后,需要消耗换行符

        scanner.nextLine(); // 消耗换行符

        

        // 读取单个字符

        System.out.print("性别(M/F):");

        char gender = scanner.nextLine().charAt(0);

        

        // 输出结果

        System.out.println("\n===== 个人信息 =====");

        System.out.println("姓名:" + name);

        System.out.println("年龄:" + age);

        System.out.println("身高:" + height + "米");

        System.out.println("是否学生:" + isStudent);

        System.out.println("性别:" + gender);

        

        // 关闭Scanner

        scanner.close();

    }

}

6.3 Scanner常用方法

import java.util.Scanner;



public class ScannerMethods {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        

        // 常用方法

        System.out.print("输入一行字符串:");

        String line = scanner.nextLine(); // 读取一行

        

        System.out.print("输入一个整数:");

        int intVal = scanner.nextInt(); // 读取整数

        

        System.out.print("输入一个浮点数:");

        double doubleVal = scanner.nextDouble(); // 读取浮点数

        

        System.out.print("输入一个单词:");

        String word = scanner.next(); // 读取到空白符

        

        System.out.print("输入一个布尔值:");

        boolean boolVal = scanner.nextBoolean(); // 读取布尔值

        

        // 判断是否有输入

        if (scanner.hasNext()) {

            System.out.println("有输入");

        }

        

        // 判断是否有整数输入

        if (scanner.hasNextInt()) {

            int num = scanner.nextInt();

            System.out.println("整数:" + num);

        }

        

        scanner.close();

    }

}

6.4 输入 - BufferedReader(高效输入)

import java.io.*;



public class BufferedReaderDemo {

    public static void main(String[] args) {

        // 使用BufferedReader(效率更高,适合大量输入)

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        

        try {

            System.out.print("姓名:");

            String name = reader.readLine();

            

            System.out.print("年龄:");

            int age = Integer.parseInt(reader.readLine());

            

            System.out.print("成绩:");

            double score = Double.parseDouble(reader.readLine());

            

            System.out.println("姓名:" + name + ",年龄:" + age + ",成绩:" + score);

            

            reader.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

6.5 与C语言的对比

对比项C语言Java
输出printf() / puts() / putchar()System.out.print() / println() / printf()
输入scanf() / gets() / getchar()Scanner 类 / BufferedReader
格式化printf 格式字符串printf 类似,但略有差异
字符串输入需要预分配字符数组动态字符串,无需预分配
错误处理返回值检查异常处理

7. 完整示例:学生成绩管理系统(简易版)

import java.util.Scanner;



public class StudentGradeSystem {

    // 常量定义

    public static final int MAX_STUDENTS = 100;

    public static final int PASS_SCORE = 60;

    

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        

        // 变量定义

        String[] names = new String[MAX_STUDENTS];

        int[] scores = new int[MAX_STUDENTS];

        int studentCount = 0;

        

        System.out.println("===== 学生成绩管理系统 =====");

        

        while (true) {

            System.out.println("\n1. 添加学生");

            System.out.println("2. 查看所有学生");

            System.out.println("3. 统计信息");

            System.out.println("4. 退出");

            System.out.print("请选择:");

            

            int choice = scanner.nextInt();

            scanner.nextLine(); // 消耗换行符

            

            switch (choice) {

                case 1:

                    if (studentCount >= MAX_STUDENTS) {

                        System.out.println("学生数量已达上限!");

                        break;

                    }

                    System.out.print("姓名:");

                    names[studentCount] = scanner.nextLine();

                    System.out.print("成绩:");

                    scores[studentCount] = scanner.nextInt();

                    scanner.nextLine();

                    studentCount++;

                    System.out.println("添加成功!");

                    break;

                    

                case 2:

                    System.out.println("\n===== 学生列表 =====");

                    System.out.printf("%-10s %-10s %-10s\n", "序号", "姓名", "成绩");

                    System.out.println("------------------------");

                    for (int i = 0; i < studentCount; i++) {

                        String status = scores[i] >= PASS_SCORE ? "及格" : "不及格";

                        System.out.printf("%-10d %-10s %-10d (%s)\n", 

                                          i + 1, names[i], scores[i], status);

                    }

                    break;

                    

                case 3:

                    if (studentCount == 0) {

                        System.out.println("暂无学生数据!");

                        break;

                    }

                    int sum = 0;

                    int maxScore = 0;

                    int minScore = 100;

                    int passCount = 0;

                    String maxName = "", minName = "";

                    

                    for (int i = 0; i < studentCount; i++) {

                        sum += scores[i];

                        if (scores[i] > maxScore) {

                            maxScore = scores[i];

                            maxName = names[i];

                        }

                        if (scores[i] < minScore) {

                            minScore = scores[i];

                            minName = names[i];

                        }

                        if (scores[i] >= PASS_SCORE) {

                            passCount++;

                        }

                    }

                    

                    double average = (double) sum / studentCount;

                    double passRate = (double) passCount / studentCount * 100;

                    

                    System.out.println("\n===== 统计信息 =====");

                    System.out.printf("学生总数:%d\n", studentCount);

                    System.out.printf("平均成绩:%.2f\n", average);

                    System.out.printf("最高分:%d(%s)\n", maxScore, maxName);

                    System.out.printf("最低分:%d(%s)\n", minScore, minName);

                    System.out.printf("及格人数:%d\n", passCount);

                    System.out.printf("及格率:%.1f%%\n", passRate);

                    break;

                    

                case 4:

                    System.out.println("程序退出,再见!");

                    scanner.close();

                    return;

                    

                default:

                    System.out.println("无效选择,请重新输入!");

            }

        }

    }

}

8. 常见错误与最佳实践

8.1 常见错误

public class CommonErrors {

    public static void main(String[] args) {

        // 错误1:未初始化变量

        int x;

        // System.out.println(x); // 编译错误:变量未初始化

        

        // 错误2:类型不匹配

        // int num = 3.14; // 编译错误:不兼容的类型

        int num = (int) 3.14; // 正确:强制转换

        

        // 错误3:字符串比较使用 ==

        String str1 = "Hello";

        String str2 = new String("Hello");

        System.out.println(str1 == str2); // false,比较的是引用

        System.out.println(str1.equals(str2)); // true,比较内容

        

        // 错误4:Scanner的nextInt后使用nextLine

        Scanner sc = new Scanner(System.in);

        System.out.print("年龄:");

        int age = sc.nextInt();

        // sc.nextLine(); // 需要消耗换行符

        System.out.print("姓名:");

        String name = sc.nextLine(); // 会读取到空字符串

        

        sc.close();

    }

}

8.2 最佳实践

public class BestPractices {

    // 1. 常量使用 final static

    public static final int MAX_SIZE = 100;

    

    // 2. 变量命名采用驼峰命名法

    int studentAge = 18;

    String studentName = "张三";

    

    // 3. 局部变量在使用前初始化

    public void method() {

        int count = 0; // 显式初始化

        // 使用count...

    }

    

    // 4. 使用 try-with-resources 自动关闭资源

    public void readFile() {

        try (Scanner scanner = new Scanner(System.in)) {

            String input = scanner.nextLine();

            System.out.println(input);

        } // 自动关闭scanner

    }

    

    // 5. 使用 StringBuilder 拼接字符串

    public void stringConcat() {

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < 100; i++) {

            sb.append(i).append(", ");

        }

        String result = sb.toString();

    }

}

9. 总结

9.1 核心知识点对比表

知识点                      C语言                                                   Java

程序结构               函数为主体                               类为主体,方法在类中

主函数                   int main()                                  public static void main(String[] args)

常量                       #define / const                         final

变量类型               平台相关大小                           平台无关,JVM定义

字符串                   字符数组                                  String类(不可变)

输入                       scanf()                                     Scanner类 / BufferedReader

输出                       printf()                                      System.out.println() / printf()

内存管理                 手动                                        自动垃圾回收

9.2 入门要点总结

1. Java是纯面向对象语言:所有代码都在类中

2. 类型严格:变量必须先声明后使用,类型检查严格

3. 跨平台性:一次编译,到处运行(需要JVM)

4. 自动内存管理:程序员无需关心内存分配释放

5. 丰富的类库:JDK提供了大量现成的类

记住:从C语言转向Java,最大的转变是从面向过程思维转向面向对象思维,理解“一切皆对象”的理念是学习Java的关键!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SegmentFault 咖啡馆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值