🚀 第一阶段:Java基础入门②Java基础语法
💡 学习目标:掌握Java基础语法,理解变量、数据类型、运算符和基本输入输出
📝 Java语法基础
🎯 Java语法特点
🌟 Java语法设计理念:简洁、清晰、易读
✨ 核心语法规则
📋 Java语法规则
│
├── 🔤 大小写敏感
│ ├── Hello ≠ hello ≠ HELLO
│ └── 变量名、类名、方法名都区分大小写
│
├── 📝 标识符规则
│ ├── 字母、数字、下划线、美元符号
│ ├── 不能以数字开头
│ └── 不能使用Java关键字
│
├── 🎯 命名约定
│ ├── 类名:PascalCase (HelloWorld)
│ ├── 方法名:camelCase (getName)
│ ├── 变量名:camelCase (userName)
│ └── 常量名:UPPER_CASE (MAX_SIZE)
│
└── 📄 文件结构
├── 包声明 (package)
├── 导入语句 (import)
├── 类定义 (class)
└── 方法定义 (method)
🔑 Java关键字
| 类别 | 关键字 | 说明 |
|---|---|---|
| 🏗️ 类相关 | class, interface, extends, implements | 定义类和接口 |
| 🔒 访问控制 | public, private, protected | 控制访问权限 |
| 🔢 数据类型 | int, double, boolean, char | 基本数据类型 |
| 🔄 流程控制 | if, else, for, while, switch | 控制程序流程 |
| 🎯 修饰符 | static, final, abstract | 修饰类、方法、变量 |
⚠️ 注意事项
• Java关键字不能用作变量名、方法名或类名
• 关键字都是小写字母
• 保留字(如goto、const)虽然不使用,但也不能作为标识符
• Java关键字不能用作变量名、方法名或类名
• 关键字都是小写字母
• 保留字(如goto、const)虽然不使用,但也不能作为标识符
📄 Java程序结构
🏗️ 基本程序结构
💻 标准Java程序结构
// 📦 包声明(可选)
package com.example.demo;
// 📚 导入语句(可选)
import java.util.Scanner;
import java.util.Date;
/**
* 📝 类注释
* 这是一个示例Java类
*/
public class JavaSyntaxDemo {
// 🔢 类变量(静态变量)
public static final String COMPANY_NAME = "Java学习";
// 📦 实例变量
private String userName;
private int userAge;
// 🚪 程序入口点
public static void main(String[] args) {
// 📢 输出欢迎信息
System.out.println("🎉 欢迎学习Java基础语法!");
// 🎯 创建对象并调用方法
JavaSyntaxDemo demo = new JavaSyntaxDemo();
demo.showUserInfo("张三", 25);
}
// 📝 实例方法
public void showUserInfo(String name, int age) {
this.userName = name;
this.userAge = age;
System.out.println("👤 用户姓名:" + userName);
System.out.println("🎂 用户年龄:" + userAge);
}
}
🎨 代码风格规范
📏 代码格式化规范
• 缩进:使用4个空格或1个Tab
• 大括号:开括号不换行,闭括号单独一行
• 空格:运算符前后加空格
• 注释:单行用//,多行用/* */
• 缩进:使用4个空格或1个Tab
• 大括号:开括号不换行,闭括号单独一行
• 空格:运算符前后加空格
• 注释:单行用//,多行用/* */
🔢 数据类型详解
🎯 Java数据类型分类
📊 Java数据类型体系:基本类型 + 引用类型
🔢 Java数据类型
│
├── 🎯 基本数据类型 (Primitive Types)
│ ├── 🔢 整数类型
│ │ ├── byte (1字节, -128 ~ 127)
│ │ ├── short (2字节, -32,768 ~ 32,767)
│ │ ├── int (4字节, -2^31 ~ 2^31-1)
│ │ └── long (8字节, -2^63 ~ 2^63-1)
│ │
│ ├── 💫 浮点类型
│ │ ├── float (4字节, 单精度)
│ │ └── double (8字节, 双精度)
│ │
│ ├── 🔤 字符类型
│ │ └── char (2字节, Unicode字符)
│ │
│ └── ✅ 布尔类型
│ └── boolean (true/false)
│
└── 📦 引用数据类型 (Reference Types)
├── 🏗️ 类 (Class)
├── 🔗 接口 (Interface)
└── 📋 数组 (Array)
🔢 基本数据类型详解
1️⃣ 整数类型
💻 整数类型示例
public class IntegerTypes {
public static void main(String[] args) {
// 🔢 byte类型 (-128 ~ 127)
byte smallNumber = 100;
System.out.println("byte值: " + smallNumber);
// 🔢 short类型 (-32,768 ~ 32,767)
short mediumNumber = 30000;
System.out.println("short值: " + mediumNumber);
// 🔢 int类型 (默认整数类型)
int normalNumber = 2000000;
System.out.println("int值: " + normalNumber);
// 🔢 long类型 (需要L后缀)
long bigNumber = 9000000000L;
System.out.println("long值: " + bigNumber);
// 🎨 不同进制表示
int decimal = 100; // 十进制
int binary = 0b1100100; // 二进制 (Java 7+)
int octal = 0144; // 八进制
int hex = 0x64; // 十六进制
System.out.println("十进制: " + decimal);
System.out.println("二进制: " + binary);
System.out.println("八进制: " + octal);
System.out.println("十六进制: " + hex);
}
}
| 类型 | 字节数 | 取值范围 | 默认值 | 使用场景 |
|---|---|---|---|---|
byte | 1 | -128 ~ 127 | 0 | 节省内存的小整数 |
short | 2 | -32,768 ~ 32,767 | 0 | 中等范围整数 |
int | 4 | -2,147,483,648 ~ 2,147,483,647 | 0 | 最常用的整数类型 |
long | 8 | -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 | 0L | 大整数运算 |
2️⃣ 浮点类型
💻 浮点类型示例
public class FloatingTypes {
public static void main(String[] args) {
// 💫 float类型 (需要f后缀)
float price = 99.99f;
System.out.println("商品价格: " + price);
// 💫 double类型 (默认浮点类型)
double pi = 3.14159265359;
System.out.println("圆周率: " + pi);
// 🔬 科学计数法
double scientific = 1.23e-4; // 0.000123
System.out.println("科学计数法: " + scientific);
// ⚠️ 浮点数精度问题
double result = 0.1 + 0.2;
System.out.println("0.1 + 0.2 = " + result); // 可能不等于0.3
// 🎯 特殊值
double positiveInfinity = Double.POSITIVE_INFINITY;
double negativeInfinity = Double.NEGATIVE_INFINITY;
double notANumber = Double.NaN;
System.out.println("正无穷: " + positiveInfinity);
System.out.println("负无穷: " + negativeInfinity);
System.out.println("非数字: " + notANumber);
}
}
| 类型 | 字节数 | 精度 | 取值范围 | 默认值 |
|---|---|---|---|---|
float | 4 | 约7位有效数字 | ±3.4E±38 | 0.0f |
double | 8 | 约15位有效数字 | ±1.7E±308 | 0.0d |
⚠️ 浮点数注意事项
• 浮点数存在精度问题,不适合精确计算(如金融)
• 使用BigDecimal类进行精确的小数运算
• float字面量需要f后缀,否则默认为double
• 浮点数存在精度问题,不适合精确计算(如金融)
• 使用BigDecimal类进行精确的小数运算
• float字面量需要f后缀,否则默认为double
3️⃣ 字符类型
💻 字符类型示例
public class CharacterType {
public static void main(String[] args) {
// 🔤 字符字面量
char letter = 'A';
char chinese = '中';
char symbol = '@';
System.out.println("字母: " + letter);
System.out.println("中文: " + chinese);
System.out.println("符号: " + symbol);
// 🔢 Unicode编码
char unicodeChar = '\u4E2D'; // 中文"中"的Unicode
System.out.println("Unicode字符: " + unicodeChar);
// 🎯 转义字符
char newline = '\n'; // 换行
char tab = '\t'; // 制表符
char backslash = '\\'; // 反斜杠
char quote = '\''; // 单引号
System.out.println("转义字符演示:");
System.out.println("第一行" + newline + "第二行");
System.out.println("制表符" + tab + "对齐");
System.out.println("反斜杠: " + backslash);
System.out.println("单引号: " + quote);
// 🔄 字符与数字转换
char digit = '5';
int number = digit - '0'; // 字符转数字
System.out.println("字符'5'转为数字: " + number);
char nextChar = (char)(letter + 1); // 下一个字符
System.out.println("A的下一个字符: " + nextChar);
}
}
4️⃣ 布尔类型
💻 布尔类型示例
public class BooleanType {
public static void main(String[] args) {
// ✅ 布尔字面量
boolean isStudent = true;
boolean isWorking = false;
System.out.println("是学生: " + isStudent);
System.out.println("在工作: " + isWorking);
// 🔍 比较运算结果
int age = 18;
boolean isAdult = age >= 18;
boolean isMinor = age < 18;
System.out.println("年龄: " + age);
System.out.println("是成年人: " + isAdult);
System.out.println("是未成年人: " + isMinor);
// 🔄 逻辑运算
boolean canVote = isAdult && isStudent;
boolean needGuardian = isMinor || !isWorking;
System.out.println("可以投票: " + canVote);
System.out.println("需要监护人: " + needGuardian);
}
}
💡 布尔类型特点
• 只有两个值:true 和 false
• 不能与数字类型相互转换
• 常用于条件判断和逻辑运算
• 默认值为false
• 只有两个值:true 和 false
• 不能与数字类型相互转换
• 常用于条件判断和逻辑运算
• 默认值为false
📦 变量的声明与使用
🎯 变量基础概念
📦 变量:存储数据的容器,具有名称、类型和值
🔧 变量声明语法
📝 变量声明格式
// 🎯 基本语法
数据类型 变量名; // 声明变量
数据类型 变量名 = 初始值; // 声明并初始化
// 💻 实际示例
int age; // 声明整型变量
int score = 95; // 声明并初始化
String name = "张三"; // 声明字符串变量
// 🔄 多变量声明
int x, y, z; // 声明多个同类型变量
int a = 1, b = 2, c = 3; // 声明并初始化多个变量
🏷️ 变量命名规范
✅ 命名规则(必须遵守)
✅ 合法的变量名
• 以字母、下划线(_)或美元符号($)开头
• 后续字符可以是字母、数字、下划线或美元符号
• 区分大小写
• 不能使用Java关键字
• 以字母、下划线(_)或美元符号($)开头
• 后续字符可以是字母、数字、下划线或美元符号
• 区分大小写
• 不能使用Java关键字
❌ 非法的变量名
• 以数字开头:
• 包含特殊字符:
• 使用关键字:
• 以数字开头:
2name
• 包含特殊字符:
user-name,
user@email
• 使用关键字:
int,
class,
public
🎨 命名约定(建议遵守)
💻 命名约定示例
public class NamingConventions {
// 🔢 常量:全大写,下划线分隔
public static final int MAX_SIZE = 100;
public static final String DEFAULT_NAME = "未知";
// 📦 实例变量:驼峰命名法
private String userName;
private int userAge;
private boolean isActive;
// 🎯 局部变量:驼峰命名法
public void processData() {
String firstName = "张";
String lastName = "三";
int totalScore = 0;
boolean hasPermission = true;
// 🔄 循环变量:简短有意义
for (int i = 0; i < 10; i++) {
// 处理逻辑
}
// 📋 集合变量:复数形式
List<String> studentNames = new ArrayList<>();
Map<String, Integer> scoreMap = new HashMap<>();
}
}
| 类型 | 命名约定 | 示例 | 说明 |
|---|---|---|---|
| 🔢 常量 | UPPER_CASE | MAX_SIZE, PI | 全大写,下划线分隔 |
| 📦 变量 | camelCase | userName, totalScore | 首字母小写的驼峰 |
| 🏗️ 类名 | PascalCase | StudentInfo, DataProcessor | 首字母大写的驼峰 |
| 📝 方法名 | camelCase | getName(), calculateTotal() | 动词开头的驼峰 |
🔄 变量的作用域
📍 作用域类型
🎯 Java变量作用域
│
├── 🏗️ 类变量 (Static Variables)
│ ├── 作用域:整个类
│ ├── 生命周期:程序运行期间
│ └── 访问:类名.变量名
│
├── 📦 实例变量 (Instance Variables)
│ ├── 作用域:整个对象
│ ├── 生命周期:对象存在期间
│ └── 访问:对象.变量名
│
├── 🎯 局部变量 (Local Variables)
│ ├── 作用域:声明的代码块内
│ ├── 生命周期:代码块执行期间
│ └── 访问:直接使用变量名
│
└── 🔄 参数变量 (Parameter Variables)
├── 作用域:方法内部
├── 生命周期:方法执行期间
└── 访问:直接使用参数名
💻 作用域示例
public class VariableScope {
// 🏗️ 类变量(静态变量)
public static int classVariable = 100;
// 📦 实例变量
private String instanceVariable = "实例变量";
public void demonstrateScope(String parameter) { // 🔄 参数变量
// 🎯 局部变量
int localVariable = 50;
System.out.println("类变量: " + classVariable);
System.out.println("实例变量: " + instanceVariable);
System.out.println("参数变量: " + parameter);
System.out.println("局部变量: " + localVariable);
// 🔄 代码块作用域
if (true) {
int blockVariable = 25; // 只在if块内有效
System.out.println("块变量: " + blockVariable);
}
// System.out.println(blockVariable); // ❌ 编译错误
// 🔄 循环作用域
for (int i = 0; i < 3; i++) { // i只在循环内有效
System.out.println("循环变量: " + i);
}
// System.out.println(i); // ❌ 编译错误
}
public static void main(String[] args) {
VariableScope obj = new VariableScope();
obj.demonstrateScope("传入的参数");
// 🏗️ 访问类变量
System.out.println("通过类名访问: " + VariableScope.classVariable);
}
}
🎯 变量初始化
🔧 默认值规则
| 数据类型 | 默认值 | 说明 |
|---|---|---|
byte, short, int | 0 | 整数类型默认为0 |
long | 0L | 长整型默认为0L |
float | 0.0f | 单精度浮点默认为0.0f |
double | 0.0d | 双精度浮点默认为0.0d |
char | ‘\u0000’ | 字符类型默认为空字符 |
boolean | false | 布尔类型默认为false |
| 引用类型 | null | 对象引用默认为null |
⚠️ 重要提醒
• 实例变量和类变量有默认值
• 局部变量必须显式初始化才能使用
• 使用未初始化的局部变量会导致编译错误
• 实例变量和类变量有默认值
• 局部变量必须显式初始化才能使用
• 使用未初始化的局部变量会导致编译错误
💻 变量初始化示例
public class VariableInitialization {
// 📦 实例变量(有默认值)
private int instanceInt; // 默认值:0
private boolean instanceBool; // 默认值:false
private String instanceString; // 默认值:null
public void demonstrateInitialization() {
// 🎯 局部变量(必须初始化)
int localInt;
// System.out.println(localInt); // ❌ 编译错误:未初始化
localInt = 10; // ✅ 初始化后可以使用
System.out.println("局部变量: " + localInt);
// ✅ 声明时初始化
int initializedVar = 20;
System.out.println("初始化变量: " + initializedVar);
// 📦 显示实例变量的默认值
System.out.println("实例int默认值: " + instanceInt);
System.out.println("实例boolean默认值: " + instanceBool);
System.out.println("实例String默认值: " + instanceString);
}
public static void main(String[] args) {
VariableInitialization obj = new VariableInitialization();
obj.demonstrateInitialization();
}
}
🔄 类型转换
🎯 类型转换概述
🔄 类型转换:将一种数据类型的值转换为另一种数据类型
📊 转换类型分类
🔄 Java类型转换
│
├── 🔼 自动类型转换 (隐式转换)
│ ├── 小范围 → 大范围
│ ├── 精度不丢失
│ └── 编译器自动完成
│
└── 🔽 强制类型转换 (显式转换)
├── 大范围 → 小范围
├── 可能丢失精度
└── 需要强制转换操作符
🔼 自动类型转换(隐式转换)
📈 转换规则图
🔼 自动类型转换路径
byte → short → int → long → float → double
↓ ↓ ↓ ↓ ↓
char ────────→ int → long → float → double
📏 转换规则:
• 容量小的类型自动转换为容量大的类型
• 整数类型可以自动转换为浮点类型
• char可以自动转换为int及更大的类型
💻 自动转换示例
public class AutomaticConversion {
public static void main(String[] args) {
// 🔼 整数类型自动转换
byte byteValue = 10;
short shortValue = byteValue; // byte → short
int intValue = shortValue; // short → int
long longValue = intValue; // int → long
System.out.println("byte → short: " + shortValue);
System.out.println("short → int: " + intValue);
System.out.println("int → long: " + longValue);
// 🔼 整数到浮点数转换
float floatValue = longValue; // long → float
double doubleValue = floatValue; // float → double
System.out.println("long → float: " + floatValue);
System.out.println("float → double: " + doubleValue);
// 🔤 字符类型转换
char charValue = 'A';
int charToInt = charValue; // char → int (ASCII值)
System.out.println("字符'A': " + charValue);
System.out.println("'A'的ASCII值: " + charToInt);
// 🔄 混合运算中的自动转换
int intNum = 10;
double doubleNum = 3.14;
double result = intNum + doubleNum; // int自动转换为double
System.out.println("混合运算结果: " + result);
}
}
🔽 强制类型转换(显式转换)
⚠️ 强制转换语法
📝 强制转换语法
// 🎯 基本语法
目标类型 变量名 = (目标类型) 源变量;
// 💻 实际示例
double doubleValue = 3.14;
int intValue = (int) doubleValue; // 强制转换为int
long longValue = 1000L;
int intFromLong = (int) longValue; // 强制转换为int
float floatValue = 99.99f;
int intFromFloat = (int) floatValue; // 强制转换为int
💻 强制转换示例
public class ExplicitConversion {
public static void main(String[] args) {
// 🔽 浮点数到整数转换(截断小数部分)
double pi = 3.14159;
int intPi = (int) pi;
System.out.println("π的值: " + pi);
System.out.println("强制转换为int: " + intPi); // 输出:3
// 🔽 大整数到小整数转换
long bigNumber = 300L;
byte smallByte = (byte) bigNumber;
System.out.println("long值: " + bigNumber);
System.out.println("转换为byte: " + smallByte); // 可能溢出
// ⚠️ 数据溢出示例
int maxInt = Integer.MAX_VALUE;
byte overflowByte = (byte) maxInt;
System.out.println("int最大值: " + maxInt);
System.out.println("溢出后的byte值: " + overflowByte);
// 🔤 数字到字符转换
int asciiValue = 65;
char character = (char) asciiValue;
System.out.println("ASCII 65对应字符: " + character); // 输出:A
// 🔄 字符到数字转换
char digit = '9';
int number = digit - '0'; // 字符运算转换
System.out.println("字符'9'转为数字: " + number);
// 🎯 布尔类型不能转换
// boolean flag = true;
// int boolToInt = (int) flag; // ❌ 编译错误
}
}
⚠️ 强制转换注意事项
• 可能导致数据丢失或精度损失
• 大数值转换为小类型可能发生溢出
• 浮点数转整数会截断小数部分
• boolean类型不能与其他类型相互转换
• 可能导致数据丢失或精度损失
• 大数值转换为小类型可能发生溢出
• 浮点数转整数会截断小数部分
• boolean类型不能与其他类型相互转换
🎯 类型提升规则
📊 运算中的类型提升
💻 类型提升示例
public class TypePromotion {
public static void main(String[] args) {
// 🔼 byte和short运算提升为int
byte b1 = 10;
byte b2 = 20;
// byte result = b1 + b2; // ❌ 编译错误
int result = b1 + b2; // ✅ 正确
System.out.println("byte运算结果: " + result);
// 🔼 char运算提升为int
char c1 = 'A';
char c2 = 'B';
int charResult = c1 + c2; // char提升为int
System.out.println("字符运算结果: " + charResult);
// 🔼 混合类型运算
int intValue = 10;
float floatValue = 3.5f;
float mixedResult = intValue + floatValue; // int提升为float
System.out.println("混合运算结果: " + mixedResult);
// 🔼 表达式中的最高类型
byte byteVal = 1;
short shortVal = 2;
int intVal = 3;
long longVal = 4L;
float floatVal = 5.0f;
// 结果类型为float(表达式中的最高类型)
float expressionResult = byteVal + shortVal + intVal + longVal + floatVal;
System.out.println("表达式结果: " + expressionResult);
}
}
📋 类型提升规则总结
| 运算情况 | 提升规则 | 结果类型 |
|---|---|---|
byte + byte | 提升为int | int |
short + short | 提升为int | int |
char + char | 提升为int | int |
int + long | int提升为long | long |
int + float | int提升为float | float |
float + double | float提升为double | double |
💡 类型提升记忆口诀
• byte、short、char运算必提升为int
• 有long则long,有float则float,有double则double
• 表达式结果类型取决于参与运算的最高类型
• byte、short、char运算必提升为int
• 有long则long,有float则float,有double则double
• 表达式结果类型取决于参与运算的最高类型
⚡ 运算符
🎯 运算符分类
⚡ 运算符:用于执行特定数学或逻辑操作的符号
⚡ Java运算符分类
│
├── 🔢 算术运算符
│ ├── + (加法)
│ ├── - (减法)
│ ├── * (乘法)
│ ├── / (除法)
│ └── % (取模)
│
├── 🔄 赋值运算符
│ ├── = (赋值)
│ ├── += (加等)
│ ├── -= (减等)
│ ├── *= (乘等)
│ └── /= (除等)
│
├── 🔍 比较运算符
│ ├── == (等于)
│ ├── != (不等于)
│ ├── > (大于)
│ ├── < (小于)
│ ├── >= (大于等于)
│ └── <= (小于等于)
│
├── 🧠 逻辑运算符
│ ├── && (逻辑与)
│ ├── || (逻辑或)
│ └── ! (逻辑非)
│
├── 🔄 自增自减运算符
│ ├── ++ (自增)
│ └── -- (自减)
│
└── 🎯 三元运算符
└── ?: (条件运算符)
🔢 算术运算符
💻 算术运算符示例
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 15;
int b = 4;
// 🔢 基本算术运算
int addition = a + b; // 加法
int subtraction = a - b; // 减法
int multiplication = a * b; // 乘法
int division = a / b; // 除法(整数除法)
int modulus = a % b; // 取模(余数)
System.out.println("a = " + a + ", b = " + b);
System.out.println("a + b = " + addition); // 19
System.out.println("a - b = " + subtraction); // 11
System.out.println("a * b = " + multiplication); // 60
System.out.println("a / b = " + division); // 3 (整数除法)
System.out.println("a % b = " + modulus); // 3 (余数)
// 💫 浮点数除法
double doubleA = 15.0;
double doubleB = 4.0;
double doubleDivision = doubleA / doubleB;
System.out.println("浮点数除法: " + doubleA + " / " + doubleB + " = " + doubleDivision);
// ⚠️ 除零异常
try {
int result = a / 0; // 运行时异常
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
}
// 🎯 取模运算的应用
int number = 17;
boolean isEven = (number % 2) == 0;
boolean isOdd = (number % 2) == 1;
System.out.println(number + " 是偶数: " + isEven);
System.out.println(number + " 是奇数: " + isOdd);
}
}
| 运算符 | 名称 | 示例 | 结果 | 说明 |
|---|---|---|---|---|
+ | 加法 | 5 + 3 | 8 | 数值相加 |
- | 减法 | 5 - 3 | 2 | 数值相减 |
* | 乘法 | 5 * 3 | 15 | 数值相乘 |
/ | 除法 | 5 / 3 | 1 | 整数除法取整 |
% | 取模 | 5 % 3 | 2 | 取余数 |
🔄 赋值运算符
💻 赋值运算符示例
public class AssignmentOperators {
public static void main(String[] args) {
int x = 10; // 基本赋值
System.out.println("初始值 x = " + x);
// 🔄 复合赋值运算符
x += 5; // 等价于 x = x + 5
System.out.println("x += 5 后,x = " + x); // 15
x -= 3; // 等价于 x = x - 3
System.out.println("x -= 3 后,x = " + x); // 12
x *= 2; // 等价于 x = x * 2
System.out.println("x *= 2 后,x = " + x); // 24
x /= 4; // 等价于 x = x / 4
System.out.println("x /= 4 后,x = " + x); // 6
x %= 4; // 等价于 x = x % 4
System.out.println("x %= 4 后,x = " + x); // 2
// 🎯 字符串连接赋值
String message = "Hello";
message += " World"; // 字符串连接
message += "!";
System.out.println("字符串连接结果: " + message); // Hello World!
// 🔄 多重赋值
int a, b, c;
a = b = c = 100; // 从右到左赋值
System.out.println("多重赋值: a=" + a + ", b=" + b + ", c=" + c);
}
}
| 运算符 | 名称 | 示例 | 等价形式 | 说明 |
|---|---|---|---|---|
= | 赋值 | x = 5 | - | 将右边的值赋给左边 |
+= | 加等 | x += 3 | x = x + 3 | 加法后赋值 |
-= | 减等 | x -= 3 | x = x - 3 | 减法后赋值 |
*= | 乘等 | x *= 3 | x = x * 3 | 乘法后赋值 |
/= | 除等 | x /= 3 | x = x / 3 | 除法后赋值 |
%= | 模等 | x %= 3 | x = x % 3 | 取模后赋值 |
🔍 比较运算符
💻 比较运算符示例
public class ComparisonOperators {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 10;
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
// 🔍 基本比较运算
boolean equal = (a == c); // 等于
boolean notEqual = (a != b); // 不等于
boolean greater = (b > a); // 大于
boolean less = (a < b); // 小于
boolean greaterEqual = (a >= c); // 大于等于
boolean lessEqual = (a <= b); // 小于等于
System.out.println("a == c: " + equal); // true
System.out.println("a != b: " + notEqual); // true
System.out.println("b > a: " + greater); // true
System.out.println("a < b: " + less); // true
System.out.println("a >= c: " + greaterEqual); // true
System.out.println("a <= b: " + lessEqual); // true
// 🔤 字符比较
char char1 = 'A';
char char2 = 'B';
boolean charComparison = char1 < char2; // 比较ASCII值
System.out.println("'A' < 'B': " + charComparison); // true
// 📝 字符串比较(注意:不能用==比较内容)
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
System.out.println("str1 == str2: " + (str1 == str2)); // true (字符串池)
System.out.println("str1 == str3: " + (str1 == str3)); // false (不同对象)
System.out.println("str1.equals(str3): " + str1.equals(str3)); // true (内容相同)
// 🎯 浮点数比较注意事项
double d1 = 0.1 + 0.2;
double d2 = 0.3;
System.out.println("0.1 + 0.2 == 0.3: " + (d1 == d2)); // 可能为false
// 正确的浮点数比较方法
double epsilon = 1e-10;
boolean floatEqual = Math.abs(d1 - d2) < epsilon;
System.out.println("浮点数近似相等: " + floatEqual);
}
}
| 运算符 | 名称 | 示例 | 结果类型 | 说明 |
|---|---|---|---|---|
== | 等于 | a == b | boolean | 值相等返回true |
!= | 不等于 | a != b | boolean | 值不等返回true |
> | 大于 | a > b | boolean | a大于b返回true |
< | 小于 | a < b | boolean | a小于b返回true |
>= | 大于等于 | a >= b | boolean | a大于等于b返回true |
<= | 小于等于 | a <= b | boolean | a小于等于b返回true |
🧠 逻辑运算符
💻 逻辑运算符示例
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
boolean c = true;
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
// 🧠 逻辑与 (&&) - 短路运算
boolean andResult = a && c; // true && true = true
boolean andResult2 = a && b; // true && false = false
boolean andResult3 = b && c; // false && true = false
System.out.println("a && c: " + andResult); // true
System.out.println("a && b: " + andResult2); // false
System.out.println("b && c: " + andResult3); // false
// 🧠 逻辑或 (||) - 短路运算
boolean orResult = a || b; // true || false = true
boolean orResult2 = b || c; // false || true = true
boolean orResult3 = b || false; // false || false = false
System.out.println("a || b: " + orResult); // true
System.out.println("b || c: " + orResult2); // true
System.out.println("b || false: " + orResult3); // false
// 🧠 逻辑非 (!)
boolean notA = !a; // !true = false
boolean notB = !b; // !false = true
System.out.println("!a: " + notA); // false
System.out.println("!b: " + notB); // true
// 🎯 复合逻辑表达式
int age = 25;
boolean hasLicense = true;
boolean canDrive = (age >= 18) && hasLicense;
System.out.println("年龄: " + age + ", 有驾照: " + hasLicense);
System.out.println("可以开车: " + canDrive);
// 🔄 短路运算演示
int x = 5;
boolean shortCircuit = (x > 10) && (++x > 0); // ++x不会执行
System.out.println("短路运算后 x = " + x); // x仍为5
boolean noShortCircuit = (x < 10) && (++x > 0); // ++x会执行
System.out.println("非短路运算后 x = " + x); // x变为6
}
}
| 运算符 | 名称 | 示例 | 说明 | 短路特性 |
|---|---|---|---|---|
&& | 逻辑与 | a && b | 两个都为true才返回true | 左边为false时不计算右边 |
| ` | ` | 逻辑或 | `a | |
! | 逻辑非 | !a | 取反,true变false,false变true | 无短路 |
🔄 自增自减运算符
💻 自增自减运算符示例
public class IncrementDecrementOperators {
public static void main(String[] args) {
int a = 5;
int b = 5;
// 🔄 前置自增/自减(先运算,后使用)
int preIncrement = ++a; // a先自增为6,然后赋值给preIncrement
System.out.println("前置自增: a = " + a + ", preIncrement = " + preIncrement);
int preDecrement = --b; // b先自减为4,然后赋值给preDecrement
System.out.println("前置自减: b = " + b + ", preDecrement = " + preDecrement);
// 🔄 后置自增/自减(先使用,后运算)
int c = 5;
int d = 5;
int postIncrement = c++; // c的值5先赋值给postIncrement,然后c自增为6
System.out.println("后置自增: c = " + c + ", postIncrement = " + postIncrement);
int postDecrement = d--; // d的值5先赋值给postDecrement,然后d自减为4
System.out.println("后置自减: d = " + d + ", postDecrement = " + postDecrement);
// 🎯 在表达式中的应用
int x = 10;
int y = 20;
int result1 = x++ + ++y; // x=10参与运算后自增为11,y先自增为21再参与运算
System.out.println("x++ + ++y = " + result1 + ", x = " + x + ", y = " + y);
// 🔄 循环中的常见用法
System.out.println("循环计数演示:");
for (int i = 0; i < 5; i++) { // 后置自增
System.out.print(i + " ");
}
System.out.println();
// ⚠️ 注意事项:避免在同一表达式中多次修改同一变量
int problematic = 5;
// int bad = problematic++ + ++problematic; // 未定义行为,避免使用
}
}
| 运算符 | 名称 | 示例 | 执行顺序 | 返回值 |
|---|---|---|---|---|
++var | 前置自增 | ++a | 先自增,后使用 | 自增后的值 |
var++ | 后置自增 | a++ | 先使用,后自增 | 自增前的值 |
--var | 前置自减 | --a | 先自减,后使用 | 自减后的值 |
var-- | 后置自减 | a-- | 先使用,后自减 | 自减前的值 |
🎯 三元运算符
💻 三元运算符示例
public class TernaryOperator {
public static void main(String[] args) {
// 🎯 基本语法:条件 ? 值1 : 值2
int a = 10;
int b = 20;
// 🔍 找出较大值
int max = (a > b) ? a : b;
System.out.println("较大值: " + max); // 20
// 🔍 找出较小值
int min = (a < b) ? a : b;
System.out.println("较小值: " + min); // 10
// 🎯 判断奇偶性
int number = 17;
String parity = (number % 2 == 0) ? "偶数" : "奇数";
System.out.println(number + " 是 " + parity);
// 🎯 成绩等级判断
int score = 85;
String grade = (score >= 90) ? "优秀" :
(score >= 80) ? "良好" :
(score >= 70) ? "中等" :
(score >= 60) ? "及格" : "不及格";
System.out.println("成绩 " + score + " 等级: " + grade);
// 🎯 空值检查
String name = null;
String displayName = (name != null) ? name : "匿名用户";
System.out.println("显示名称: " + displayName);
// 🎯 绝对值计算
int value = -15;
int absoluteValue = (value >= 0) ? value : -value;
System.out.println(value + " 的绝对值: " + absoluteValue);
// 🔄 与if-else的对比
// 使用三元运算符(简洁)
String result1 = (a > 0) ? "正数" : "非正数";
// 使用if-else(更清晰)
String result2;
if (a > 0) {
result2 = "正数";
} else {
result2 = "非正数";
}
System.out.println("三元运算符结果: " + result1);
System.out.println("if-else结果: " + result2);
}
}
💡 三元运算符使用建议
• 适用于简单的条件赋值
• 嵌套使用时要注意可读性
• 复杂逻辑建议使用if-else语句
• 两个分支的返回类型要兼容
• 适用于简单的条件赋值
• 嵌套使用时要注意可读性
• 复杂逻辑建议使用if-else语句
• 两个分支的返回类型要兼容
📊 运算符优先级
| 优先级 | 运算符 | 结合性 | 说明 |
|---|---|---|---|
| 1 | () [] . | 左到右 | 括号、数组、成员访问 |
| 2 | ++ -- ! ~ | 右到左 | 一元运算符 |
| 3 | * / % | 左到右 | 乘除取模 |
| 4 | + - | 左到右 | 加减 |
| 5 | << >> >>> | 左到右 | 位移运算 |
| 6 | < <= > >= | 左到右 | 关系运算 |
| 7 | == != | 左到右 | 相等性判断 |
| 8 | & | 左到右 | 按位与 |
| 9 | ^ | 左到右 | 按位异或 |
| 10 | ` | ` | 左到右 |
| 11 | && | 左到右 | 逻辑与 |
| 12 | ` | ` | |
| 13 | ?: | 右到左 | 三元运算符 |
| 14 | = += -= 等 | 右到左 | 赋值运算符 |
💻 运算符优先级示例
public class OperatorPrecedence {
public static void main(String[] args) {
// 🎯 算术运算符优先级
int result1 = 2 + 3 * 4; // 先乘后加:2 + 12 = 14
int result2 = (2 + 3) * 4; // 括号优先:5 * 4 = 20
System.out.println("2 + 3 * 4 = " + result1); // 14
System.out.println("(2 + 3) * 4 = " + result2); // 20
// 🎯 比较和逻辑运算符优先级
boolean result3 = 5 > 3 && 2 < 4; // 先比较后逻辑:true && true = true
boolean result4 = 5 > 3 || 2 > 4; // 先比较后逻辑:true || false = true
System.out.println("5 > 3 && 2 < 4 = " + result3); // true
System.out.println("5 > 3 || 2 > 4 = " + result4); // true
// 🎯 自增运算符优先级
int a = 5;
int result5 = ++a * 2; // 先自增后乘法:6 * 2 = 12
System.out.println("++a * 2 = " + result5 + ", a = " + a);
int b = 5;
int result6 = b++ * 2; // 先乘法后自增:5 * 2 = 10
System.out.println("b++ * 2 = " + result6 + ", b = " + b);
// 🎯 复杂表达式
int x = 10, y = 20, z = 30;
boolean complexResult = x < y && y < z || x > z;
// 等价于:((x < y) && (y < z)) || (x > z)
// 即:(true && true) || false = true
System.out.println("复杂表达式结果: " + complexResult);
}
}
💡 优先级记忆技巧
• 括号优先级最高,可以改变运算顺序
• 一元运算符 > 算术运算符 > 比较运算符 > 逻辑运算符 > 赋值运算符
• 不确定时使用括号明确运算顺序
• 复杂表达式建议拆分为多个简单表达式
• 括号优先级最高,可以改变运算顺序
• 一元运算符 > 算术运算符 > 比较运算符 > 逻辑运算符 > 赋值运算符
• 不确定时使用括号明确运算顺序
• 复杂表达式建议拆分为多个简单表达式
🔀 流程控制
🎯 流程控制概述
🔀 流程控制:控制程序执行顺序的语句,包括条件判断、循环和跳转
📊 流程控制分类
🔀 Java流程控制语句
│
├── 🔍 条件语句 (Selection Statements)
│ ├── if语句
│ ├── if-else语句
│ ├── if-else if-else语句
│ └── switch语句
│
├── 🔄 循环语句 (Loop Statements)
│ ├── for循环
│ ├── while循环
│ ├── do-while循环
│ └── 增强for循环(for-each)
│
└── 🎯 跳转语句 (Jump Statements)
├── break语句
├── continue语句
└── return语句
🔍 条件语句
1️⃣ if语句
💻 if语句示例
public class IfStatement {
public static void main(String[] args) {
int score = 85;
// 🔍 简单if语句
if (score >= 60) {
System.out.println("恭喜!考试及格了!");
}
// 🔍 if-else语句
if (score >= 90) {
System.out.println("优秀!");
} else {
System.out.println("继续努力!");
}
// 🔍 多重if-else语句
if (score >= 90) {
System.out.println("等级:优秀");
} else if (score >= 80) {
System.out.println("等级:良好");
} else if (score >= 70) {
System.out.println("等级:中等");
} else if (score >= 60) {
System.out.println("等级:及格");
} else {
System.out.println("等级:不及格");
}
// 🔍 嵌套if语句
if (score >= 60) {
if (score >= 90) {
System.out.println("可以申请奖学金!");
} else {
System.out.println("继续努力争取奖学金!");
}
} else {
System.out.println("需要补考!");
}
}
}
2️⃣ switch语句
💻 switch语句示例
public class SwitchStatement {
public static void main(String[] args) {
// 🔍 基本switch语句
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期日");
break;
default:
System.out.println("无效的星期");
}
// 🔍 字符switch语句
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("优秀!90-100分");
break;
case 'B':
System.out.println("良好!80-89分");
break;
case 'C':
System.out.println("中等!70-79分");
break;
case 'D':
System.out.println("及格!60-69分");
break;
case 'F':
System.out.println("不及格!0-59分");
break;
default:
System.out.println("无效的等级");
}
// 🔍 字符串switch语句(Java 7+)
String season = "春天";
switch (season) {
case "春天":
System.out.println("万物复苏的季节");
break;
case "夏天":
System.out.println("炎热的季节");
break;
case "秋天":
System.out.println("收获的季节");
break;
case "冬天":
System.out.println("寒冷的季节");
break;
default:
System.out.println("未知的季节");
}
}
}
🔄 循环语句
1️⃣ for循环
💻 for循环示例
public class ForLoop {
public static void main(String[] args) {
// 🔄 基本for循环
System.out.println("=== 基本for循环 ===");
for (int i = 1; i <= 5; i++) {
System.out.println("第" + i + "次循环");
}
// 🔄 计算1到100的和
System.out.println("\n=== 计算1到100的和 ===");
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("1到100的和:" + sum);
// 🔄 嵌套for循环 - 打印乘法表
System.out.println("\n=== 九九乘法表 ===");
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "×" + i + "=" + (i * j) + "\t");
}
System.out.println();
}
// 🔄 增强for循环(for-each)
System.out.println("\n=== 增强for循环 ===");
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println("数字:" + number);
}
String[] fruits = {"苹果", "香蕉", "橙子"};
for (String fruit : fruits) {
System.out.println("水果:" + fruit);
}
}
}
2️⃣ while循环
💻 while循环示例
public class WhileLoop {
public static void main(String[] args) {
// 🔄 基本while循环
System.out.println("=== 基本while循环 ===");
int count = 1;
while (count <= 5) {
System.out.println("计数:" + count);
count++;
}
// 🔄 计算阶乘
System.out.println("\n=== 计算5的阶乘 ===");
int n = 5;
int factorial = 1;
int i = 1;
while (i <= n) {
factorial *= i;
i++;
}
System.out.println(n + "的阶乘:" + factorial);
// 🔄 用户输入验证
System.out.println("\n=== 输入验证示例 ===");
java.util.Scanner scanner = new java.util.Scanner(System.in);
int number;
System.out.print("请输入一个1-10之间的数字:");
number = scanner.nextInt();
while (number < 1 || number > 10) {
System.out.print("输入无效!请重新输入1-10之间的数字:");
number = scanner.nextInt();
}
System.out.println("您输入的数字是:" + number);
scanner.close();
}
}
3️⃣ do-while循环
💻 do-while循环示例
public class DoWhileLoop {
public static void main(String[] args) {
// 🔄 基本do-while循环
System.out.println("=== 基本do-while循环 ===");
int count = 1;
do {
System.out.println("执行第" + count + "次");
count++;
} while (count <= 5);
// 🔄 菜单系统示例
System.out.println("\n=== 简单菜单系统 ===");
java.util.Scanner scanner = new java.util.Scanner(System.in);
int choice;
do {
System.out.println("\n=== 主菜单 ===");
System.out.println("1. 查看信息");
System.out.println("2. 添加数据");
System.out.println("3. 删除数据");
System.out.println("0. 退出系统");
System.out.print("请选择操作:");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("正在查看信息...");
break;
case 2:
System.out.println("正在添加数据...");
break;
case 3:
System.out.println("正在删除数据...");
break;
case 0:
System.out.println("感谢使用,再见!");
break;
default:
System.out.println("无效选择,请重新输入!");
}
} while (choice != 0);
scanner.close();
}
}
🎯 跳转语句
1️⃣ break语句
💻 break语句示例
public class BreakStatement {
public static void main(String[] args) {
// 🎯 在循环中使用break
System.out.println("=== 查找特定数字 ===");
int[] numbers = {1, 3, 5, 7, 9, 2, 4, 6, 8};
int target = 7;
boolean found = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
System.out.println("找到数字" + target + ",位置:" + i);
found = true;
break; // 找到后立即退出循环
}
}
if (!found) {
System.out.println("未找到数字" + target);
}
// 🎯 在嵌套循环中使用break
System.out.println("\n=== 嵌套循环中的break ===");
outer: // 标签
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
System.out.println("遇到特殊条件,退出所有循环");
break outer; // 退出标签指定的循环
}
System.out.println("i=" + i + ", j=" + j);
}
}
}
}
2️⃣ continue语句
💻 continue语句示例
public class ContinueStatement {
public static void main(String[] args) {
// 🎯 跳过偶数,只打印奇数
System.out.println("=== 只打印奇数 ===");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // 跳过偶数
}
System.out.println("奇数:" + i);
}
// 🎯 跳过特定条件
System.out.println("\n=== 跳过负数和零 ===");
int[] numbers = {-2, -1, 0, 1, 2, 3, -4, 5};
for (int number : numbers) {
if (number <= 0) {
continue; // 跳过负数和零
}
System.out.println("正数:" + number);
}
// 🎯 在嵌套循环中使用continue
System.out.println("\n=== 嵌套循环中的continue ===");
for (int i = 1; i <= 3; i++) {
System.out.println("外层循环:" + i);
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue; // 跳过内层循环的当前迭代
}
System.out.println(" 内层循环:" + j);
}
}
}
}
🎨 流程控制综合应用
💻 综合应用:数字猜谜游戏
import java.util.Scanner;
import java.util.Random;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
System.out.println("🎮 欢迎来到数字猜谜游戏!");
boolean playAgain = true;
while (playAgain) {
// 生成1-100之间的随机数
int secretNumber = random.nextInt(100) + 1;
int attempts = 0;
int maxAttempts = 7;
boolean hasWon = false;
System.out.println("\n🎯 我想了一个1-100之间的数字,你有" + maxAttempts + "次机会猜中它!");
while (attempts < maxAttempts && !hasWon) {
System.out.print("第" + (attempts + 1) + "次猜测,请输入你的数字:");
int guess = scanner.nextInt();
attempts++;
if (guess == secretNumber) {
System.out.println("🎉 恭喜!你猜对了!数字就是" + secretNumber);
System.out.println("你用了" + attempts + "次就猜中了!");
hasWon = true;
} else if (guess < secretNumber) {
System.out.println("📈 太小了!再试试更大的数字");
} else {
System.out.println("📉 太大了!再试试更小的数字");
}
if (!hasWon && attempts < maxAttempts) {
System.out.println("还有" + (maxAttempts - attempts) + "次机会");
}
}
if (!hasWon) {
System.out.println("😢 很遗憾,你没有猜中!正确答案是:" + secretNumber);
}
// 询问是否再玩一次
System.out.print("\n🔄 想再玩一次吗?(y/n):");
String response = scanner.next();
playAgain = response.equalsIgnoreCase("y") || response.equalsIgnoreCase("yes");
}
System.out.println("👋 感谢游戏,再见!");
scanner.close();
}
}
💡 流程控制最佳实践
• 合理使用缩进,保持代码可读性
• 避免过深的嵌套,考虑提取方法
• 在switch语句中不要忘记break
• 使用有意义的变量名和注释
• 注意循环的终止条件,避免无限循环
• 合理使用缩进,保持代码可读性
• 避免过深的嵌套,考虑提取方法
• 在switch语句中不要忘记break
• 使用有意义的变量名和注释
• 注意循环的终止条件,避免无限循环
📥 输入输出操作
📤 输出操作
🖨️ System.out输出方法
💻 基本输出方法
public class OutputOperations {
public static void main(String[] args) {
// 📢 println() - 输出并换行
System.out.println("Hello World!");
System.out.println("这是第二行");
// 📢 print() - 输出不换行
System.out.print("不换行输出1 ");
System.out.print("不换行输出2 ");
System.out.println(); // 手动换行
// 📢 printf() - 格式化输出
String name = "张三";
int age = 25;
double salary = 8500.50;
System.out.printf("姓名:%s,年龄:%d,薪资:%.2f%n", name, age, salary);
// 🎯 变量输出
int number = 42;
String text = "Java";
boolean flag = true;
System.out.println("数字:" + number);
System.out.println("文本:" + text);
System.out.println("布尔值:" + flag);
// 🎨 特殊字符输出
System.out.println("制表符:\t制表符效果");
System.out.println("换行符:\n这是新的一行");
System.out.println("反斜杠:\\");
System.out.println("双引号:\"Hello\"");
// 🔢 数值格式化
double pi = Math.PI;
System.out.println("π的值:" + pi);
System.out.printf("π保留2位小数:%.2f%n", pi);
System.out.printf("π保留4位小数:%.4f%n", pi);
}
}
🎨 格式化输出详解
💻 printf格式化示例
public class FormattedOutput {
public static void main(String[] args) {
// 🔢 整数格式化
int number = 123;
System.out.printf("整数:%d%n", number);
System.out.printf("5位宽度右对齐:%5d%n", number);
System.out.printf("5位宽度左对齐:%-5d%n", number);
System.out.printf("前导零:%05d%n", number);
// 💫 浮点数格式化
double value = 123.456789;
System.out.printf("浮点数:%f%n", value);
System.out.printf("保留2位小数:%.2f%n", value);
System.out.printf("科学计数法:%e%n", value);
System.out.printf("自动选择格式:%g%n", value);
// 🔤 字符串格式化
String name = "Java";
System.out.printf("字符串:%s%n", name);
System.out.printf("10位宽度右对齐:%10s%n", name);
System.out.printf("10位宽度左对齐:%-10s%n", name);
// 🔤 字符格式化
char letter = 'A';
System.out.printf("字符:%c%n", letter);
System.out.printf("字符的ASCII值:%d%n", (int)letter);
// ✅ 布尔值格式化
boolean flag = true;
System.out.printf("布尔值:%b%n", flag);
System.out.printf("布尔值(大写):%B%n", flag);
// 🎯 综合格式化示例
String studentName = "李四";
int studentAge = 20;
double studentScore = 95.5;
char studentGrade = 'A';
System.out.printf("学生信息:姓名=%s, 年龄=%d, 成绩=%.1f, 等级=%c%n",
studentName, studentAge, studentScore, studentGrade);
// 📊 表格格式输出
System.out.println("学生成绩表:");
System.out.printf("%-10s %5s %8s %6s%n", "姓名", "年龄", "成绩", "等级");
System.out.printf("%-10s %5d %8.1f %6c%n", "张三", 18, 88.5, 'B');
System.out.printf("%-10s %5d %8.1f %6c%n", "李四", 19, 92.0, 'A');
System.out.printf("%-10s %5d %8.1f %6c%n", "王五", 20, 76.5, 'C');
}
}
| 格式符 | 数据类型 | 说明 | 示例 |
|---|---|---|---|
%d | 整数 | 十进制整数 | %d → 123 |
%f | 浮点数 | 小数形式 | %.2f → 123.46 |
%e | 浮点数 | 科学计数法 | %e → 1.234568e+02 |
%s | 字符串 | 字符串 | %s → Hello |
%c | 字符 | 单个字符 | %c → A |
%b | 布尔值 | true/false | %b → true |
%n | 换行符 | 平台无关的换行 | 相当于\n |
📥 输入操作
🎯 Scanner类基础
💻 Scanner基本使用
import java.util.Scanner; // 导入Scanner类
public class InputOperations {
public static void main(String[] args) {
// 🎯 创建Scanner对象
Scanner scanner = new Scanner(System.in);
// 📝 提示用户输入
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(); // 读取布尔值
// 📤 输出用户信息
System.out.println("\n=== 用户信息 ===");
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
System.out.printf("身高:%.2f米%n", height);
System.out.println("是否为学生:" + isStudent);
// 🔒 关闭Scanner(良好习惯)
scanner.close();
}
}
🔧 Scanner方法详解
💻 Scanner各种输入方法
import java.util.Scanner;
public class ScannerMethods {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 🔤 字符串输入
System.out.print("输入一个单词:");
String word = scanner.next(); // 读取单个单词(遇到空格停止)
System.out.println("单词:" + word);
// 清除缓冲区的换行符
scanner.nextLine();
System.out.print("输入一行文本:");
String line = scanner.nextLine(); // 读取整行(包含空格)
System.out.println("整行:" + line);
// 🔢 数值输入
System.out.print("输入一个字节(-128~127):");
byte byteValue = scanner.nextByte();
System.out.print("输入一个短整数:");
short shortValue = scanner.nextShort();
System.out.print("输入一个整数:");
int intValue = scanner.nextInt();
System.out.print("输入一个长整数:");
long longValue = scanner.nextLong();
System.out.print("输入一个单精度浮点数:");
float floatValue = scanner.nextFloat();
System.out.print("输入一个双精度浮点数:");
double doubleValue = scanner.nextDouble();
// ✅ 布尔值输入
System.out.print("输入布尔值(true/false):");
boolean boolValue = scanner.nextBoolean();
// 📊 输出所有输入的值
System.out.println("\n=== 输入汇总 ===");
System.out.println("byte: " + byteValue);
System.out.println("short: " + shortValue);
System.out.println("int: " + intValue);
System.out.println("long: " + longValue);
System.out.println("float: " + floatValue);
System.out.println("double: " + doubleValue);
System.out.println("boolean: " + boolValue);
scanner.close();
}
}
| 方法 | 返回类型 | 说明 | 示例 |
|---|---|---|---|
next() | String | 读取下一个单词 | 输入"Hello World"返回"Hello" |
nextLine() | String | 读取整行 | 输入"Hello World"返回"Hello World" |
nextInt() | int | 读取整数 | 输入"123"返回123 |
nextDouble() | double | 读取浮点数 | 输入"3.14"返回3.14 |
nextBoolean() | boolean | 读取布尔值 | 输入"true"返回true |
hasNext() | boolean | 检查是否有下一个输入 | 有输入返回true |
hasNextInt() | boolean | 检查下一个输入是否为整数 | 是整数返回true |
⚠️ Scanner使用注意事项
💻 Scanner常见问题及解决方案
import java.util.Scanner;
public class ScannerIssues {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// ⚠️ 问题1:nextInt()后使用nextLine()的问题
System.out.print("输入年龄:");
int age = scanner.nextInt();
// 这里需要消费掉nextInt()留下的换行符
scanner.nextLine(); // 消费换行符
System.out.print("输入姓名:");
String name = scanner.nextLine();
System.out.println("年龄:" + age + ",姓名:" + name);
// ⚠️ 问题2:输入验证
System.out.print("请输入一个整数:");
while (!scanner.hasNextInt()) {
System.out.print("输入无效,请输入一个整数:");
scanner.next(); // 消费无效输入
}
int validNumber = scanner.nextInt();
System.out.println("有效整数:" + validNumber);
// ⚠️ 问题3:异常处理
scanner.nextLine(); // 消费换行符
System.out.print("输入一个浮点数:");
try {
String input = scanner.nextLine();
double number = Double.parseDouble(input);
System.out.println("浮点数:" + number);
} catch (NumberFormatException e) {
System.out.println("输入格式错误:" + e.getMessage());
}
scanner.close();
}
}
⚠️ Scanner使用建议
• 使用完Scanner后要调用close()方法
• nextInt()等方法后使用nextLine()前要先消费换行符
• 使用hasNextXxx()方法进行输入验证
• 对于可能出错的输入使用异常处理
• 一个程序中尽量只创建一个Scanner对象
• 使用完Scanner后要调用close()方法
• nextInt()等方法后使用nextLine()前要先消费换行符
• 使用hasNextXxx()方法进行输入验证
• 对于可能出错的输入使用异常处理
• 一个程序中尽量只创建一个Scanner对象
🎯 实战练习:简单计算器
💻 综合练习:控制台计算器
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("🧮 欢迎使用简单计算器!");
System.out.println("支持运算:+ - * / %");
System.out.println("输入 'quit' 退出程序");
while (true) {
try {
// 📥 获取第一个数字
System.out.print("\n请输入第一个数字(或输入quit退出):");
String input1 = scanner.nextLine();
if ("quit".equalsIgnoreCase(input1)) {
System.out.println("👋 感谢使用,再见!");
break;
}
double num1 = Double.parseDouble(input1);
// 📥 获取运算符
System.out.print("请输入运算符 (+, -, *, /, %):");
String operator = scanner.nextLine();
// 📥 获取第二个数字
System.out.print("请输入第二个数字:");
double num2 = Double.parseDouble(scanner.nextLine());
// 🧮 执行计算
double result = 0;
boolean validOperation = true;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
System.out.println("❌ 错误:除数不能为零!");
validOperation = false;
} else {
result = num1 / num2;
}
break;
case "%":
if (num2 == 0) {
System.out.println("❌ 错误:除数不能为零!");
validOperation = false;
} else {
result = num1 % num2;
}
break;
default:
System.out.println("❌ 错误:不支持的运算符!");
validOperation = false;
}
// 📤 显示结果
if (validOperation) {
System.out.printf("✅ 计算结果:%.2f %s %.2f = %.2f%n",
num1, operator, num2, result);
}
} catch (NumberFormatException e) {
System.out.println("❌ 错误:请输入有效的数字!");
}
}
scanner.close();
}
}
📝 本章小结
🎉 恭喜!你已经掌握了Java基础语法的核心内容!
✅ 学习成果检查清单
🎯 知识掌握情况
| 学习内容 | 掌握程度 | 检查方式 |
|---|---|---|
| 📝 Java语法规则 | ✅ 已掌握 | 能说出标识符命名规则 |
| 🔢 数据类型 | ✅ 已掌握 | 熟悉8种基本数据类型 |
| 📦 变量使用 | ✅ 已掌握 | 能正确声明和初始化变量 |
| 🔄 类型转换 | ✅ 已掌握 | 理解自动和强制转换 |
| ⚡ 运算符 | ✅ 已掌握 | 掌握各种运算符的使用 |
| 📥 输入输出 | ✅ 已掌握 | 能使用Scanner和System.out |
🏆 技能成就解锁
📝 语法规范专家
掌握Java语法规则和命名约定
掌握Java语法规则和命名约定
🔢 数据类型大师
熟练使用各种数据类型
熟练使用各种数据类型
⚡ 运算符专家
掌握所有运算符的使用
掌握所有运算符的使用
📥 输入输出能手
能够处理用户交互
能够处理用户交互
🎯 核心知识点总结
📊 数据类型速查表
| 类型 | 字节 | 取值范围 | 默认值 | 示例 |
|---|---|---|---|---|
byte | 1 | -128 ~ 127 | 0 | byte b = 100; |
short | 2 | -32,768 ~ 32,767 | 0 | short s = 1000; |
int | 4 | -2^31 ~ 2^31-1 | 0 | int i = 100000; |
long | 8 | -2^63 ~ 2^63-1 | 0L | long l = 100000L; |
float | 4 | ±3.4E±38 | 0.0f | float f = 3.14f; |
double | 8 | ±1.7E±308 | 0.0d | double d = 3.14; |
char | 2 | 0 ~ 65535 | ‘\u0000’ | char c = 'A'; |
boolean | - | true/false | false | boolean b = true; |
⚡ 运算符优先级速记
🎯 运算符优先级(从高到低)
1. () [] . - 括号、数组、成员访问
2. ++ -- ! ~ - 一元运算符
3. * / % - 乘除取模
4. + - - 加减
5. < <= > >= - 关系运算
6. == != - 相等性判断
7. && - 逻辑与
8. || - 逻辑或
9. ?: - 三元运算符
10. = += -= *= /= - 赋值运算符
🔄 类型转换规则
🔼 自动类型转换路径
byte → short → int → long → float → double
↓ ↓ ↓ ↓ ↓
char ────────→ int → long → float → double
🔽 强制类型转换
目标类型 变量 = (目标类型) 源变量;
📋 实战练习作业
💪 实践出真知:通过练习巩固所学知识
🎯 基础练习(必做)
练习1:变量声明与初始化 ⭐⭐
// 声明并初始化各种类型的变量
// 包括:姓名、年龄、身高、是否为学生、成绩等
练习2:运算符综合应用 ⭐⭐⭐
// 编写程序计算:
// 1. 两个数的四则运算
// 2. 判断一个数是否为偶数
// 3. 比较三个数的大小
练习3:类型转换练习 ⭐⭐⭐
// 练习自动和强制类型转换
// 观察精度损失和数据溢出现象
🚀 进阶练习(选做)
练习4:用户信息管理系统 ⭐⭐⭐⭐
// 使用Scanner获取用户输入
// 包括:姓名、年龄、身高、体重
// 计算BMI指数并给出健康建议
练习5:数学计算器增强版 ⭐⭐⭐⭐⭐
// 在简单计算器基础上增加:
// 1. 历史记录功能
// 2. 更多数学函数(平方、开方等)
// 3. 错误处理和输入验证
🔍 常见错误与解决方案
❌ 常见错误类型
| 错误类型 | 原因 | 解决方案 |
|---|---|---|
| 变量未初始化 | 使用未赋值的局部变量 | 声明时初始化或使用前赋值 |
| 类型不匹配 | 将大类型赋值给小类型 | 使用强制类型转换 |
| 除零异常 | 除数为0 | 添加条件判断 |
| 数组越界 | 访问不存在的数组索引 | 检查数组长度 |
| 输入格式错误 | Scanner读取错误格式 | 添加异常处理 |
🛠️ 调试技巧
🔧 调试建议
• 使用System.out.println()输出中间结果
• 检查变量的值和类型
• 逐步执行代码,定位问题所在
• 使用IDE的调试功能设置断点
• 阅读错误信息,理解错误原因
• 使用System.out.println()输出中间结果
• 检查变量的值和类型
• 逐步执行代码,定位问题所在
• 使用IDE的调试功能设置断点
• 阅读错误信息,理解错误原因
🗺️ 专栏学习路径图
📈 Java程序员从0到1成长路径
🎯 第一阶段:Java基础入门 (4-6周)
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 1.开发环境 │───▶│ 2.基础语法 │───▶│ 3.面向对象 │───▶│ 4.核心API │
│ 搭建 │ │ │ │ 编程基础 │ │ │
│ ✅ 已完成 │ │ ✅ 已完成 │ │ 🎯 下一步 │ │ 📅 计划中 │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
🚀 第二阶段:Java进阶技能 (4-6周)
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 1.高级特性 │ │ 2.I/O与网络 │ │ 3.新特性 │ │ 4.工具框架 │
│ │ │ 编程 │ │ │ │ 入门 │
│ 📅 计划中 │ │ 📅 计划中 │ │ 📅 计划中 │ │ 📅 计划中 │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
🎯 第三阶段:项目实战 (4-8周)
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 1.小型项目 │ │ 2.Web开发 │ │ 3.Spring │ │ 4.数据库与 │
│ 开发 │ │ 基础 │ │ 框架入门 │ │ 持久层 │
│ 📅 计划中 │ │ 📅 计划中 │ │ 📅 计划中 │ │ 📅 计划中 │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
🏆 第四阶段:职业发展 (持续更新)
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 1.代码质量 │ │ 2.开发工具 │ │ 3.面试准备 │ │ 4.职业规划 │
│ 与规范 │ │ 链 │ │ │ │ │
│ 📅 计划中 │ │ 📅 计划中 │ │ 📅 计划中 │ │ 📅 计划中 │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
📋 第一阶段学习进度
| 章节 | 主要内容 | 预计时间 | 难度 | 状态 |
|---|---|---|---|---|
| 📚 1.开发环境搭建 | JDK安装、Hello World、IDE使用 | 1-2天 | ⭐⭐ | ✅ 已完成 |
| 📝 2.基础语法 | 变量、数据类型、运算符、流程控制 | 1周 | ⭐⭐⭐ | ✅ 已完成 |
| 🏗️ 3.面向对象基础 | 类与对象、封装、继承、多态 | 1-2周 | ⭐⭐⭐⭐ | 🎯 下一步 |
| 🔧 4.核心API | String、集合框架、异常处理 | 1周 | ⭐⭐⭐ | 📅 计划中 |
🎯 当前进度
• 第一阶段进度:50% (2/4章节完成)
• 下一步:学习面向对象编程基础
• 建议:巩固基础语法,准备进入面向对象世界
• 重点:理解类与对象的概念,掌握封装原理
• 第一阶段进度:50% (2/4章节完成)
• 下一步:学习面向对象编程基础
• 建议:巩固基础语法,准备进入面向对象世界
• 重点:理解类与对象的概念,掌握封装原理
📚 推荐学习资源
🌟 在线资源
| 资源 | 类型 | 难度 | 推荐指数 |
|---|---|---|---|
| 📖 Oracle Java教程 | 官方教程 | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 💻 菜鸟教程Java | 中文教程 | ⭐⭐ | ⭐⭐⭐⭐ |
| 🎥 慕课网Java课程 | 视频教程 | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| 📝 LeetCode Java练习 | 编程练习 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
📖 经典书籍
📚 推荐阅读
• 《Java核心技术 卷I》 - 基础知识全面覆盖
• 《Head First Java》 - 生动有趣的入门书籍
• 《Java编程思想》 - 深入理解Java设计理念
• 《Effective Java》 - Java最佳实践指南
• 《Java核心技术 卷I》 - 基础知识全面覆盖
• 《Head First Java》 - 生动有趣的入门书籍
• 《Java编程思想》 - 深入理解Java设计理念
• 《Effective Java》 - Java最佳实践指南
🎬 下一章预告
🏗️ 第一阶段第3章:面向对象编程基础
🎯 下章学习内容
- 🏗️ 面向对象编程概述与四大特性
- 📦 类与对象的定义和使用
- 🔒 封装、继承与多态的原理和应用
- 🎯 抽象类与接口的设计和使用
- 🛠️ 面向对象程序设计实践
📚 学习重点
- 理解面向对象编程思想
- 掌握类和对象的基本概念
- 学会使用封装、继承、多态
- 理解抽象类与接口的区别和应用
- 能够设计简单的面向对象程序
🚀 准备好进入面向对象编程的世界了吗?
💡 学习小贴士
掌握了基础语法和流程控制,你已经具备了编程的基本能力!
接下来学习面向对象编程,这是Java编程的核心思想!
记住:从面向过程到面向对象是编程思维的重要转变! 🌟
📧 有问题?欢迎在评论区讨论交流!
⭐ 觉得有用?别忘了点赞收藏!
🔄 继续关注,更多精彩内容即将到来!

被折叠的 条评论
为什么被折叠?



