本章将详细介绍Java的基本语法,包括变量、数据类型、运算符、控制结构等核心概念,为后续的面向对象编程打下坚实基础。
3.1 Java程序结构
3.1.1 基本程序结构
// 包声明(可选)
package com.example;
// 导入语句(可选)
import java.util.Scanner;
import java.time.LocalDate;
/**
* 类的文档注释
* @author 作者名
* @version 1.0
*/
public class BasicSyntax {
// 类变量(静态变量)
private static final String COMPANY_NAME = "Example Corp";
// 实例变量
private String name;
private int age;
/**
* 主方法 - 程序入口点
* @param args 命令行参数
*/
public static void main(String[] args) {
System.out.println("Hello, Java!");
// 创建对象实例
BasicSyntax example = new BasicSyntax();
example.demonstrateBasics();
}
/**
* 演示基本语法的方法
*/
public void demonstrateBasics() {
// 局部变量
String message = "学习Java基本语法";
System.out.println(message);
}
}
3.1.2 Java语法规则
public class SyntaxRules {
public static void main(String[] args) {
// 1. Java区分大小写
int number = 10;
int Number = 20; // 这是不同的变量
System.out.println("number: " + number);
System.out.println("Number: " + Number);
// 2. 标识符命名规则
String userName = "张三"; // 驼峰命名法
final int MAX_SIZE = 100; // 常量使用大写字母和下划线
boolean isValid = true; // 布尔变量通常以is开头
// 3. 语句必须以分号结束
int a = 5;
int b = 10;
int sum = a + b;
// 4. 代码块使用大括号
if (sum > 10) {
System.out.println("和大于10");
}
// 5. 注释的使用
// 单行注释
/*
* 多行注释
* 可以跨越多行
*/
/**
* 文档注释
* 用于生成API文档
*/
}
}
3.2 变量和数据类型
3.2.1 基本数据类型
public class PrimitiveTypes {
public static void main(String[] args) {
// 整数类型
byte byteValue = 127; // 8位,范围:-128 到 127
short shortValue = 32767; // 16位,范围:-32,768 到 32,767
int intValue = 2147483647; // 32位,范围:-2^31 到 2^31-1
long longValue = 9223372036854775807L; // 64位,需要L后缀
// 浮点类型
float floatValue = 3.14f; // 32位,需要f后缀
double doubleValue = 3.141592653589793; // 64位,默认浮点类型
// 字符类型
char charValue = 'A'; // 16位Unicode字符
char unicodeChar = '\u4e2d'; // Unicode表示的中文字符'中'
// 布尔类型
boolean booleanValue = true; // 只能是true或false
// 输出各种类型的值和大小
System.out.println("=== 基本数据类型示例 ===");
System.out.println("byte: " + byteValue + ", 大小: " + Byte.BYTES + " 字节");
System.out.println("short: " + shortValue + ", 大小: " + Short.BYTES + " 字节");
System.out.println("int: " + intValue + ", 大小: " + Integer.BYTES + " 字节");
System.out.println("long: " + longValue + ", 大小: " + Long.BYTES + " 字节");
System.out.println("float: " + floatValue + ", 大小: " + Float.BYTES + " 字节");
System.out.println("double: " + doubleValue + ", 大小: " + Double.BYTES + " 字节");
System.out.println("char: " + charValue + ", Unicode: " + unicodeChar);
System.out.println("boolean: " + booleanValue);
// 类型的最大值和最小值
System.out.println("\n=== 类型范围 ===");
System.out.println("byte范围: " + Byte.MIN_VALUE + " 到 " + Byte.MAX_VALUE);
System.out.println("int范围: " + Integer.MIN_VALUE + " 到 " + Integer.MAX_VALUE);
System.out.println("double范围: " + Double.MIN_VALUE + " 到 " + Double.MAX_VALUE);
}
}
3.2.2 引用数据类型
import java.util.Arrays;
import java.time.LocalDate;
public class ReferenceTypes {
public static void main(String[] args) {
// 字符串类型
String str1 = "Hello"; // 字符串字面量
String str2 = new String("World"); // 使用构造器
String str3 = str1 + ", " + str2; // 字符串连接
System.out.println("字符串示例:");
System.out.println("str1: " + str1);
System.out.println("str2: " + str2);
System.out.println("str3: " + str3);
System.out.println("str1长度: " + str1.length());
System.out.println("str3转大写: " + str3.toUpperCase());
// 数组类型
int[] numbers = {1, 2, 3, 4, 5}; // 数组初始化
String[] names = new String[3]; // 创建指定大小的数组
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
System.out.println("\n数组示例:");
System.out.println("numbers: " + Arrays.toString(numbers));
System.out.println("names: " + Arrays.toString(names));
System.out.println("numbers长度: " + numbers.length);
// 对象类型
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1990, 5, 15);
System.out.println("\n对象示例:");
System.out.println("今天: " + today);
System.out.println("生日: " + birthday);
System.out.println("年龄: " + (today.getYear() - birthday.getYear()) + " 岁");
// null值
String nullString = null;
System.out.println("\nnull示例:");
System.out.println("nullString: " + nullString);
// 注意:访问null对象的方法会抛出NullPointerException
try {
int length = nullString.length(); // 这会抛出异常
} catch (NullPointerException e) {
System.out.println("捕获到空指针异常: " + e.getMessage());
}
}
}
3.2.3 变量声明和初始化
public class VariableDeclaration {
// 类变量(静态变量)
static int classVariable = 100;
// 实例变量
int instanceVariable;
String name = "默认名称";
public static void main(String[] args) {
// 局部变量必须初始化后才能使用
int localVariable; // 声明但未初始化
// System.out.println(localVariable); // 编译错误!
localVariable = 42; // 初始化
System.out.println("局部变量: " + localVariable);
// 变量声明的不同方式
int a = 10; // 声明并初始化
int b, c, d; // 同时声明多个变量
b = 20;
c = 30;
d = 40;
int x = 1, y = 2, z = 3; // 声明并初始化多个变量
System.out.println("多个变量: a=" + a + ", b=" + b + ", c=" + c + ", d=" + d);
System.out.println("一行声明: x=" + x + ", y=" + y + ", z=" + z);
// 常量声明
final int CONSTANT_VALUE = 100; // 局部常量
final double PI = 3.14159;
// CONSTANT_VALUE = 200; // 编译错误!常量不能重新赋值
System.out.println("常量: " + CONSTANT_VALUE + ", PI: " + PI);
// 变量作用域演示
demonstrateScope();
}
public static void demonstrateScope() {
System.out.println("\n=== 变量作用域演示 ===");
// 可以访问类变量
System.out.println("类变量: " + classVariable);
// 创建实例来访问实例变量
VariableDeclaration instance = new VariableDeclaration();
System.out.println("实例变量: " + instance.instanceVariable); // 默认值0
System.out.println("实例变量name: " + instance.name);
// 块作用域
{
int blockVariable = 50;
System.out.println("块变量: " + blockVariable);
}
// System.out.println(blockVariable); // 编译错误!超出作用域
// 循环中的变量作用域
for (int i = 0; i < 3; i++) {
int loopVariable = i * 10;
System.out.println("循环变量 i=" + i + ", loopVariable=" + loopVariable);
}
// System.out.println(i); // 编译错误!i超出作用域
}
}
3.2.4 类型转换
public class TypeConversion {
public static void main(String[] args) {
System.out.println("=== 类型转换示例 ===");
// 自动类型转换(隐式转换)
byte byteValue = 10;
short shortValue = byteValue; // byte -> short
int intValue = shortValue; // short -> int
long longValue = intValue; // int -> long
float floatValue = longValue; // long -> float
double doubleValue = floatValue; // float -> double
System.out.println("自动类型转换:");
System.out.println("byte(" + byteValue + ") -> double(" + doubleValue + ")");
// 强制类型转换(显式转换)
double d = 3.14159;
float f = (float) d; // double -> float
long l = (long) f; // float -> long
int i = (int) l; // long -> int
short s = (short) i; // int -> short
byte b = (byte) s; // short -> byte
System.out.println("\n强制类型转换:");
System.out.println("double(" + d + ") -> byte(" + b + ")");
// 精度丢失示例
double largeDouble = 123.456789;
int truncatedInt = (int) largeDouble;
System.out.println("\n精度丢失:");
System.out.println("double: " + largeDouble + " -> int: " + truncatedInt);
// 溢出示例
int largeInt = 300;
byte overflowByte = (byte) largeInt;
System.out.println("\n溢出示例:");
System.out.println("int: " + largeInt + " -> byte: " + overflowByte);
// 字符和数字的转换
char ch = 'A';
int ascii = ch; // char -> int (ASCII值)
char backToChar = (char) (ascii + 1); // int -> char
System.out.println("\n字符转换:");
System.out.println("字符 '" + ch + "' 的ASCII值: " + ascii);
System.out.println("ASCII " + (ascii + 1) + " 对应字符: '" + backToChar + "'");
// 字符串转换
String numberStr = "123";
int parsedInt = Integer.parseInt(numberStr);
double parsedDouble = Double.parseDouble("123.45");
System.out.println("\n字符串转换:");
System.out.println("字符串 '" + numberStr + "' -> int: " + parsedInt);
System.out.println("字符串 '123.45' -> double: " + parsedDouble);
// 数字转字符串
int num = 456;
String numStr = String.valueOf(num);
String numStr2 = Integer.toString(num);
String numStr3 = num + ""; // 简单方式
System.out.println("\n数字转字符串:");
System.out.println("int " + num + " -> String: '" + numStr + "'");
System.out.println("使用toString(): '" + numStr2 + "'");
System.out.println("使用连接: '" + numStr3 + "'");
}
}
3.3 运算符
3.3.1 算术运算符
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 15;
int b = 4;
System.out.println("=== 算术运算符 ===");
System.out.println("a = " + a + ", b = " + b);
// 基本算术运算
System.out.println("\n基本运算:");
System.out.println("a + b = " + (a + b)); // 加法
System.out.println("a - b = " + (a - b)); // 减法
System.out.println("a * b = " + (a * b)); // 乘法
System.out.println("a / b = " + (a / b)); // 除法(整数除法)
System.out.println("a % b = " + (a % b)); // 取模(余数)
// 浮点除法
double da = 15.0;
double db = 4.0;
System.out.println("\n浮点除法:");
System.out.println("15.0 / 4.0 = " + (da / db));
System.out.println("15 / 4.0 = " + (a / db)); // 自动类型提升
// 一元运算符
int x = 10;
System.out.println("\n一元运算符:");
System.out.println("x = " + x);
System.out.println("+x = " + (+x)); // 正号
System.out.println("-x = " + (-x)); // 负号
// 自增和自减运算符
int y = 5;
System.out.println("\n自增自减运算符:");
System.out.println("y = " + y);
System.out.println("++y = " + (++y)); // 前置自增
System.out.println("y = " + y);
System.out.println("y++ = " + (y++)); // 后置自增
System.out.println("y = " + y);
System.out.println("--y = " + (--y)); // 前置自减
System.out.println("y-- = " + (y--)); // 后置自减
System.out.println("y = " + y);
// 复合赋值运算符
int z = 10;
System.out.println("\n复合赋值运算符:");
System.out.println("z = " + z);
z += 5; // z = z + 5
System.out.println("z += 5, z = " + z);
z -= 3; // z = z - 3
System.out.println("z -= 3, z = " + z);
z *= 2; // z = z * 2
System.out.println("z *= 2, z = " + z);
z /= 4; // z = z / 4
System.out.println("z /= 4, z = " + z);
z %= 3; // z = z % 3
System.out.println("z %= 3, z = " + z);
}
}
3.3.2 关系运算符
public class RelationalOperators {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 10;
System.out.println("=== 关系运算符 ===");
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
// 比较运算符
System.out.println("\n比较运算:");
System.out.println("a == b: " + (a == b)); // 等于
System.out.println("a == c: " + (a == c));
System.out.println("a != b: " + (a != b)); // 不等于
System.out.println("a < b: " + (a < b)); // 小于
System.out.println("a > b: " + (a > b)); // 大于
System.out.println("a <= c: " + (a <= c)); // 小于等于
System.out.println("b >= a: " + (b >= a)); // 大于等于
// 字符串比较
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
String str4 = "World";
System.out.println("\n字符串比较:");
System.out.println("str1 = \"" + str1 + "\", str2 = \"" + str2 + "\"");
System.out.println("str3 = new String(\"Hello\"), str4 = \"" + str4 + "\"");
// == 比较引用
System.out.println("str1 == str2: " + (str1 == str2)); // true(字符串池)
System.out.println("str1 == str3: " + (str1 == str3)); // false(不同对象)
// equals() 比较内容
System.out.println("str1.equals(str2): " + str1.equals(str2)); // true
System.out.println("str1.equals(str3): " + str1.equals(str3)); // true
System.out.println("str1.equals(str4): " + str1.equals(str4)); // false
// compareTo() 字典序比较
System.out.println("\n字典序比较:");
System.out.println("str1.compareTo(str4): " + str1.compareTo(str4)); // 负数
System.out.println("str4.compareTo(str1): " + str4.compareTo(str1)); // 正数
System.out.println("str1.compareTo(str2): " + str1.compareTo(str2)); // 0
// 数组比较
int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};
int[] array3 = array1;
System.out.println("\n数组比较:");
System.out.println("array1 == array2: " + (array1 == array2)); // false(不同对象)
System.out.println("array1 == array3: " + (array1 == array3)); // true(同一对象)
System.out.println("Arrays.equals(array1, array2): " + java.util.Arrays.equals(array1, array2)); // true
}
}
3.3.3 逻辑运算符
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
boolean c = true;
System.out.println("=== 逻辑运算符 ===");
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
// 逻辑与(AND)
System.out.println("\n逻辑与 (&&):");
System.out.println("a && b = " + (a && b)); // true && false = false
System.out.println("a && c = " + (a && c)); // true && true = true
System.out.println("b && c = " + (b && c)); // false && true = false
// 逻辑或(OR)
System.out.println("\n逻辑或 (||):");
System.out.println("a || b = " + (a || b)); // true || false = true
System.out.println("a || c = " + (a || c)); // true || true = true
System.out.println("b || false = " + (b || false)); // false || false = false
// 逻辑非(NOT)
System.out.println("\n逻辑非 (!):");
System.out.println("!a = " + (!a)); // !true = false
System.out.println("!b = " + (!b)); // !false = true
System.out.println("!!a = " + (!!a)); // !!true = true
// 短路求值演示
System.out.println("\n短路求值演示:");
int x = 5;
int y = 0;
// 短路与:如果第一个条件为false,不会执行第二个条件
if (y != 0 && x / y > 2) {
System.out.println("不会执行到这里");
} else {
System.out.println("避免了除零错误");
}
// 短路或:如果第一个条件为true,不会执行第二个条件
if (x > 0 || x / y > 2) {
System.out.println("第一个条件为true,避免了除零错误");
}
// 复杂逻辑表达式
int age = 25;
boolean hasLicense = true;
boolean hasInsurance = false;
System.out.println("\n复杂逻辑表达式:");
System.out.println("年龄: " + age + ", 有驾照: " + hasLicense + ", 有保险: " + hasInsurance);
boolean canDrive = age >= 18 && hasLicense;
boolean canDriveLegally = canDrive && hasInsurance;
System.out.println("可以开车: " + canDrive);
System.out.println("可以合法开车: " + canDriveLegally);
// 德摩根定律演示
System.out.println("\n德摩根定律:");
boolean p = true;
boolean q = false;
System.out.println("p = " + p + ", q = " + q);
System.out.println("!(p && q) = " + !(p && q));
System.out.println("!p || !q = " + (!p || !q));
System.out.println("!(p || q) = " + !(p || q));
System.out.println("!p && !q = " + (!p && !q));
}
}
3.3.4 位运算符
public class BitwiseOperators {
public static void main(String[] args) {
int a = 12; // 二进制: 1100
int b = 10; // 二进制: 1010
System.out.println("=== 位运算符 ===");
System.out.println("a = " + a + " (二进制: " + Integer.toBinaryString(a) + ")");
System.out.println("b = " + b + " (二进制: " + Integer.toBinaryString(b) + ")");
// 位与(AND)
int andResult = a & b;
System.out.println("\na & b = " + andResult + " (二进制: " + Integer.toBinaryString(andResult) + ")");
// 位或(OR)
int orResult = a | b;
System.out.println("a | b = " + orResult + " (二进制: " + Integer.toBinaryString(orResult) + ")");
// 位异或(XOR)
int xorResult = a ^ b;
System.out.println("a ^ b = " + xorResult + " (二进制: " + Integer.toBinaryString(xorResult) + ")");
// 位非(NOT)
int notResult = ~a;
System.out.println("~a = " + notResult + " (二进制: " + Integer.toBinaryString(notResult) + ")");
// 左移位
int leftShift = a << 2;
System.out.println("\na << 2 = " + leftShift + " (二进制: " + Integer.toBinaryString(leftShift) + ")");
System.out.println("相当于 a * 2^2 = " + (a * 4));
// 右移位(算术右移)
int rightShift = a >> 2;
System.out.println("a >> 2 = " + rightShift + " (二进制: " + Integer.toBinaryString(rightShift) + ")");
System.out.println("相当于 a / 2^2 = " + (a / 4));
// 无符号右移
int unsignedRightShift = a >>> 2;
System.out.println("a >>> 2 = " + unsignedRightShift + " (二进制: " + Integer.toBinaryString(unsignedRightShift) + ")");
// 负数的位运算
int negative = -8;
System.out.println("\n负数位运算:");
System.out.println("negative = " + negative + " (二进制: " + Integer.toBinaryString(negative) + ")");
System.out.println("negative >> 2 = " + (negative >> 2) + " (二进制: " + Integer.toBinaryString(negative >> 2) + ")");
System.out.println("negative >>> 2 = " + (negative >>> 2) + " (二进制: " + Integer.toBinaryString(negative >>> 2) + ")");
// 位运算的实际应用
System.out.println("\n位运算应用:");
// 判断奇偶性
int number = 15;
boolean isOdd = (number & 1) == 1;
System.out.println(number + " 是奇数: " + isOdd);
// 交换两个数(不使用临时变量)
int x = 5, y = 10;
System.out.println("交换前: x = " + x + ", y = " + y);
x = x ^ y;
y = x ^ y;
x = x ^ y;
System.out.println("交换后: x = " + x + ", y = " + y);
// 计算2的幂
int power = 3;
int result = 1 << power; // 2^3
System.out.println("2^" + power + " = " + result);
// 检查某一位是否为1
int value = 12; // 1100
int position = 2;
boolean bitIsSet = (value & (1 << position)) != 0;
System.out.println(value + " 的第 " + position + " 位是否为1: " + bitIsSet);
}
}
3.4 控制结构
3.4.1 条件语句
import java.util.Scanner;
public class ConditionalStatements {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// if语句
System.out.println("=== if语句 ===");
int score = 85;
if (score >= 90) {
System.out.println("优秀");
}
// if-else语句
System.out.println("\n=== if-else语句 ===");
if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
// if-else if-else语句
System.out.println("\n=== if-else if-else语句 ===");
if (score >= 90) {
System.out.println("A级");
} else if (score >= 80) {
System.out.println("B级");
} else if (score >= 70) {
System.out.println("C级");
} else if (score >= 60) {
System.out.println("D级");
} else {
System.out.println("F级");
}
// 嵌套if语句
System.out.println("\n=== 嵌套if语句 ===");
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("可以开车");
} else {
System.out.println("年龄够了,但需要考驾照");
}
} else {
System.out.println("年龄不够,不能开车");
}
// 三元运算符
System.out.println("\n=== 三元运算符 ===");
int a = 10, b = 20;
int max = (a > b) ? a : b;
String result = (a > b) ? "a更大" : "b更大或相等";
System.out.println("a = " + a + ", b = " + b);
System.out.println("最大值: " + max);
System.out.println("比较结果: " + result);
// 复杂条件
System.out.println("\n=== 复杂条件 ===");
int temperature = 25;
boolean isSunny = true;
boolean isWeekend = false;
if ((temperature > 20 && temperature < 30) && isSunny && !isWeekend) {
System.out.println("适合工作日户外活动");
} else if ((temperature > 15 && temperature < 35) && isWeekend) {
System.out.println("周末可以考虑户外活动");
} else {
System.out.println("建议室内活动");
}
scanner.close();
}
}
3.4.2 switch语句
import java.time.LocalDate;
import java.time.DayOfWeek;
public class SwitchStatements {
public static void main(String[] args) {
// 传统switch语句
System.out.println("=== 传统switch语句 ===");
int dayOfWeek = 3;
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "星期一";
break;
case 2:
dayName = "星期二";
break;
case 3:
dayName = "星期三";
break;
case 4:
dayName = "星期四";
break;
case 5:
dayName = "星期五";
break;
case 6:
dayName = "星期六";
break;
case 7:
dayName = "星期日";
break;
default:
dayName = "无效的日期";
break;
}
System.out.println("第" + dayOfWeek + "天是: " + dayName);
// 没有break的情况(fall-through)
System.out.println("\n=== Fall-through示例 ===");
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
System.out.println("优秀");
break;
case 'C':
case 'D':
System.out.println("良好");
break;
case 'F':
System.out.println("需要改进");
break;
default:
System.out.println("无效成绩");
}
// 字符串switch(Java 7+)
System.out.println("\n=== 字符串switch ===");
String month = "三月";
int days;
switch (month) {
case "一月":
case "三月":
case "五月":
case "七月":
case "八月":
case "十月":
case "十二月":
days = 31;
break;
case "四月":
case "六月":
case "九月":
case "十一月":
days = 30;
break;
case "二月":
days = 28; // 简化,不考虑闰年
break;
default:
days = 0;
System.out.println("无效的月份");
}
if (days > 0) {
System.out.println(month + "有" + days + "天");
}
// 枚举switch
System.out.println("\n=== 枚举switch ===");
DayOfWeek today = LocalDate.now().getDayOfWeek();
switch (today) {
case MONDAY:
System.out.println("周一,新的开始!");
break;
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
System.out.println("工作日,继续努力!");
break;
case FRIDAY:
System.out.println("周五,快到周末了!");
break;
case SATURDAY:
case SUNDAY:
System.out.println("周末,好好休息!");
break;
}
// Java 14+ switch表达式(如果支持)
System.out.println("\n=== Switch表达式 (Java 14+) ===");
int monthNumber = 3;
// 传统方式
String season1;
switch (monthNumber) {
case 12:
case 1:
case 2:
season1 = "冬季";
break;
case 3:
case 4:
case 5:
season1 = "春季";
break;
case 6:
case 7:
case 8:
season1 = "夏季";
break;
case 9:
case 10:
case 11:
season1 = "秋季";
break;
default:
season1 = "无效月份";
}
System.out.println("第" + monthNumber + "月是" + season1);
// 使用switch表达式的方式(注释掉,因为可能不支持)
/*
String season2 = switch (monthNumber) {
case 12, 1, 2 -> "冬季";
case 3, 4, 5 -> "春季";
case 6, 7, 8 -> "夏季";
case 9, 10, 11 -> "秋季";
default -> "无效月份";
};
System.out.println("使用switch表达式: 第" + monthNumber + "月是" + season2);
*/
}
}
3.4.3 循环语句
import java.util.Scanner;
import java.util.Random;
public class LoopStatements {
public static void main(String[] args) {
// for循环
System.out.println("=== for循环 ===");
// 基本for循环
System.out.println("1到10的数字:");
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
System.out.println();
// 倒序for循环
System.out.println("\n10到1的数字:");
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println();
// 步长不为1的循环
System.out.println("\n偶数(2到20):");
for (int i = 2; i <= 20; i += 2) {
System.out.print(i + " ");
}
System.out.println();
// 嵌套for循环 - 乘法表
System.out.println("\n=== 嵌套for循环 - 九九乘法表 ===");
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();
}
// while循环
System.out.println("\n=== while循环 ===");
int count = 1;
System.out.println("使用while循环计算1到10的和:");
int sum = 0;
while (count <= 10) {
sum += count;
count++;
}
System.out.println("和为: " + sum);
// do-while循环
System.out.println("\n=== do-while循环 ===");
Scanner scanner = new Scanner(System.in);
int number;
System.out.println("猜数字游戏(1-100),输入0退出:");
Random random = new Random();
int target = random.nextInt(100) + 1;
int attempts = 0;
do {
System.out.print("请输入你的猜测: ");
number = scanner.nextInt();
if (number == 0) {
System.out.println("游戏结束!正确答案是: " + target);
break;
}
attempts++;
if (number == target) {
System.out.println("恭喜!你猜对了!用了" + attempts + "次");
break;
} else if (number < target) {
System.out.println("太小了!");
} else {
System.out.println("太大了!");
}
} while (number != target);
// 增强for循环(for-each)
System.out.println("\n=== 增强for循环 ===");
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
System.out.println("数组元素:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
System.out.println("姓名列表:");
for (String name : names) {
System.out.println("- " + name);
}
// break和continue
System.out.println("\n=== break和continue ===");
// break示例
System.out.println("break示例 - 找到第一个偶数就停止:");
int[] testNumbers = {1, 3, 5, 8, 9, 10, 11};
for (int num : testNumbers) {
if (num % 2 == 0) {
System.out.println("找到第一个偶数: " + num);
break;
}
System.out.println("检查: " + num + " (奇数)");
}
// continue示例
System.out.println("\ncontinue示例 - 只打印偶数:");
for (int num : testNumbers) {
if (num % 2 != 0) {
continue; // 跳过奇数
}
System.out.println("偶数: " + num);
}
// 标签break和continue
System.out.println("\n=== 标签break和continue ===");
outer: for (int i = 1; i <= 3; i++) {
System.out.println("外层循环 i = " + i);
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
System.out.println(" 跳出外层循环");
break outer; // 跳出外层循环
}
System.out.println(" 内层循环 j = " + j);
}
}
// 无限循环示例(注释掉避免程序卡住)
/*
System.out.println("\n=== 无限循环示例 ===");
int counter = 0;
while (true) {
System.out.println("循环次数: " + (++counter));
if (counter >= 5) {
break; // 避免真正的无限循环
}
}
*/
scanner.close();
}
}
3.5 数组
3.5.1 一维数组
import java.util.Arrays;
import java.util.Scanner;
public class OneDimensionalArrays {
public static void main(String[] args) {
// 数组声明和初始化
System.out.println("=== 数组声明和初始化 ===");
// 方式1:声明后初始化
int[] numbers1 = new int[5]; // 创建长度为5的数组
numbers1[0] = 10;
numbers1[1] = 20;
numbers1[2] = 30;
numbers1[3] = 40;
numbers1[4] = 50;
// 方式2:声明时初始化
int[] numbers2 = {1, 2, 3, 4, 5};
// 方式3:使用new关键字初始化
int[] numbers3 = new int[]{6, 7, 8, 9, 10};
// 方式4:不同的声明语法
int numbers4[] = {11, 12, 13, 14, 15}; // C风格,不推荐
System.out.println("numbers1: " + Arrays.toString(numbers1));
System.out.println("numbers2: " + Arrays.toString(numbers2));
System.out.println("numbers3: " + Arrays.toString(numbers3));
System.out.println("numbers4: " + Arrays.toString(numbers4));
// 数组属性和方法
System.out.println("\n=== 数组属性 ===");
System.out.println("numbers1长度: " + numbers1.length);
System.out.println("numbers2长度: " + numbers2.length);
// 访问数组元素
System.out.println("\n=== 访问数组元素 ===");
System.out.println("numbers2[0] = " + numbers2[0]); // 第一个元素
System.out.println("numbers2[" + (numbers2.length - 1) + "] = " + numbers2[numbers2.length - 1]); // 最后一个元素
// 修改数组元素
numbers2[2] = 100;
System.out.println("修改后的numbers2: " + Arrays.toString(numbers2));
// 遍历数组
System.out.println("\n=== 遍历数组 ===");
// 使用传统for循环
System.out.println("使用传统for循环:");
for (int i = 0; i < numbers1.length; i++) {
System.out.print(numbers1[i] + " ");
}
System.out.println();
// 使用增强for循环
System.out.println("使用增强for循环:");
for (int num : numbers2) {
System.out.print(num + " ");
}
System.out.println();
// 数组操作示例
System.out.println("\n=== 数组操作示例 ===");
// 计算数组和
int sum = 0;
for (int num : numbers1) {
sum += num;
}
System.out.println("数组和: " + sum);
// 找最大值和最小值
int max = numbers1[0];
int min = numbers1[0];
for (int i = 1; i < numbers1.length; i++) {
if (numbers1[i] > max) {
max = numbers1[i];
}
if (numbers1[i] < min) {
min = numbers1[i];
}
}
System.out.println("最大值: " + max + ", 最小值: " + min);
// 查找元素
int target = 30;
int index = -1;
for (int i = 0; i < numbers1.length; i++) {
if (numbers1[i] == target) {
index = i;
break;
}
}
if (index != -1) {
System.out.println("找到元素 " + target + " 在索引 " + index);
} else {
System.out.println("未找到元素 " + target);
}
// 数组排序
System.out.println("\n=== 数组排序 ===");
int[] unsorted = {64, 34, 25, 12, 22, 11, 90};
System.out.println("排序前: " + Arrays.toString(unsorted));
// 使用Arrays.sort()排序
Arrays.sort(unsorted);
System.out.println("排序后: " + Arrays.toString(unsorted));
// 手动实现冒泡排序
int[] bubbleSort = {64, 34, 25, 12, 22, 11, 90};
System.out.println("\n冒泡排序前: " + Arrays.toString(bubbleSort));
for (int i = 0; i < bubbleSort.length - 1; i++) {
for (int j = 0; j < bubbleSort.length - 1 - i; j++) {
if (bubbleSort[j] > bubbleSort[j + 1]) {
// 交换元素
int temp = bubbleSort[j];
bubbleSort[j] = bubbleSort[j + 1];
bubbleSort[j + 1] = temp;
}
}
}
System.out.println("冒泡排序后: " + Arrays.toString(bubbleSort));
// 数组复制
System.out.println("\n=== 数组复制 ===");
int[] original = {1, 2, 3, 4, 5};
// 方式1:使用Arrays.copyOf()
int[] copy1 = Arrays.copyOf(original, original.length);
// 方式2:使用System.arraycopy()
int[] copy2 = new int[original.length];
System.arraycopy(original, 0, copy2, 0, original.length);
// 方式3:使用clone()
int[] copy3 = original.clone();
System.out.println("原数组: " + Arrays.toString(original));
System.out.println("复制1: " + Arrays.toString(copy1));
System.out.println("复制2: " + Arrays.toString(copy2));
System.out.println("复制3: " + Arrays.toString(copy3));
// 修改原数组,观察复制数组是否受影响
original[0] = 999;
System.out.println("\n修改原数组后:");
System.out.println("原数组: " + Arrays.toString(original));
System.out.println("复制1: " + Arrays.toString(copy1)); // 不受影响
// 动态数组示例
System.out.println("\n=== 动态输入数组 ===");
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数组大小: ");
int size = scanner.nextInt();
int[] dynamicArray = new int[size];
System.out.println("请输入 " + size + " 个整数:");
for (int i = 0; i < size; i++) {
System.out.print("第" + (i + 1) + "个数: ");
dynamicArray[i] = scanner.nextInt();
}
System.out.println("你输入的数组: " + Arrays.toString(dynamicArray));
// 计算平均值
double average = 0;
for (int num : dynamicArray) {
average += num;
}
average /= dynamicArray.length;
System.out.println("平均值: " + average);
scanner.close();
}
}
3.5.2 多维数组
import java.util.Arrays;
import java.util.Random;
public class MultiDimensionalArrays {
public static void main(String[] args) {
// 二维数组
System.out.println("=== 二维数组 ===");
// 声明和初始化二维数组
int[][] matrix1 = new int[3][4]; // 3行4列
int[][] matrix2 = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// 填充matrix1
int value = 1;
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
matrix1[i][j] = value++;
}
}
// 打印二维数组
System.out.println("matrix1:");
printMatrix(matrix1);
System.out.println("\nmatrix2:");
printMatrix(matrix2);
// 访问二维数组元素
System.out.println("\n=== 访问二维数组元素 ===");
System.out.println("matrix2[1][2] = " + matrix2[1][2]); // 第2行第3列
System.out.println("matrix2行数: " + matrix2.length);
System.out.println("matrix2第一行列数: " + matrix2[0].length);
// 遍历二维数组
System.out.println("\n=== 遍历二维数组 ===");
System.out.println("使用传统for循环:");
for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[i].length; j++) {
System.out.print(matrix2[i][j] + "\t");
}
System.out.println();
}
System.out.println("\n使用增强for循环:");
for (int[] row : matrix2) {
for (int element : row) {
System.out.print(element + "\t");
}
System.out.println();
}
// 不规则二维数组(锯齿数组)
System.out.println("\n=== 不规则二维数组 ===");
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[2]; // 第一行2列
jaggedArray[1] = new int[4]; // 第二行4列
jaggedArray[2] = new int[3]; // 第三行3列
// 填充锯齿数组
Random random = new Random();
for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
jaggedArray[i][j] = random.nextInt(100);
}
}
System.out.println("锯齿数组:");
for (int i = 0; i < jaggedArray.length; i++) {
System.out.println("第" + (i + 1) + "行: " + Arrays.toString(jaggedArray[i]));
}
// 三维数组
System.out.println("\n=== 三维数组 ===");
int[][][] cube = new int[2][3][4]; // 2个3x4的矩阵
// 填充三维数组
int count = 1;
for (int i = 0; i < cube.length; i++) {
for (int j = 0; j < cube[i].length; j++) {
for (int k = 0; k < cube[i][j].length; k++) {
cube[i][j][k] = count++;
}
}
}
// 打印三维数组
System.out.println("三维数组:");
for (int i = 0; i < cube.length; i++) {
System.out.println("第" + (i + 1) + "个矩阵:");
printMatrix(cube[i]);
System.out.println();
}
// 矩阵运算示例
System.out.println("=== 矩阵运算示例 ===");
int[][] matrixA = {
{1, 2, 3},
{4, 5, 6}
};
int[][] matrixB = {
{7, 8, 9},
{10, 11, 12}
};
// 矩阵加法
int[][] sum = addMatrices(matrixA, matrixB);
System.out.println("矩阵A:");
printMatrix(matrixA);
System.out.println("矩阵B:");
printMatrix(matrixB);
System.out.println("矩阵A + B:");
printMatrix(sum);
// 矩阵转置
int[][] transposed = transposeMatrix(matrixA);
System.out.println("矩阵A的转置:");
printMatrix(transposed);
}
// 打印矩阵的辅助方法
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + "\t");
}
System.out.println();
}
}
// 矩阵加法
public static int[][] addMatrices(int[][] a, int[][] b) {
if (a.length != b.length || a[0].length != b[0].length) {
throw new IllegalArgumentException("矩阵维度不匹配");
}
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
// 矩阵转置
public static int[][] transposeMatrix(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int[][] transposed = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j];
}
}
return transposed;
}
}
3.6 方法基础
3.6.1 方法定义和调用
public class MethodBasics {
public static void main(String[] args) {
System.out.println("=== 方法基础 ===");
// 调用无参数无返回值的方法
sayHello();
// 调用有参数无返回值的方法
greetUser("张三");
// 调用有返回值的方法
int sum = addNumbers(10, 20);
System.out.println("10 + 20 = " + sum);
// 调用有多个参数的方法
double average = calculateAverage(85, 92, 78, 96, 88);
System.out.println("平均分: " + average);
// 调用返回布尔值的方法
boolean isEven = isEvenNumber(42);
System.out.println("42是偶数: " + isEven);
// 方法链式调用
String result = processString(" Hello World ");
System.out.println("处理后的字符串: '" + result + "'");
// 调用数组处理方法
int[] numbers = {5, 2, 8, 1, 9, 3};
System.out.println("\n原数组: " + java.util.Arrays.toString(numbers));
int max = findMaximum(numbers);
System.out.println("最大值: " + max);
sortArray(numbers); // 注意:这会修改原数组
System.out.println("排序后: " + java.util.Arrays.toString(numbers));
}
// 无参数无返回值的方法
public static void sayHello() {
System.out.println("Hello, World!");
}
// 有参数无返回值的方法
public static void greetUser(String name) {
System.out.println("你好, " + name + "!");
}
// 有参数有返回值的方法
public static int addNumbers(int a, int b) {
return a + b;
}
// 多个参数的方法
public static double calculateAverage(int... scores) {
if (scores.length == 0) {
return 0;
}
int sum = 0;
for (int score : scores) {
sum += score;
}
return (double) sum / scores.length;
}
// 返回布尔值的方法
public static boolean isEvenNumber(int number) {
return number % 2 == 0;
}
// 字符串处理方法
public static String processString(String input) {
if (input == null) {
return "";
}
return input.trim().toLowerCase();
}
// 数组处理方法 - 查找最大值
public static int findMaximum(int[] array) {
if (array == null || array.length == 0) {
throw new IllegalArgumentException("数组不能为空");
}
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
// 数组排序方法(修改原数组)
public static void sortArray(int[] array) {
if (array == null || array.length <= 1) {
return;
}
// 简单的冒泡排序
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
// 交换元素
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
3.6.2 方法重载
public class MethodOverloading {
public static void main(String[] args) {
System.out.println("=== 方法重载示例 ===");
// 调用不同版本的print方法
print("Hello");
print(42);
print(3.14);
print(true);
// 调用不同版本的add方法
System.out.println("\n=== 加法方法重载 ===");
System.out.println("add(5, 3) = " + add(5, 3));
System.out.println("add(2.5, 3.7) = " + add(2.5, 3.7));
System.out.println("add(1, 2, 3) = " + add(1, 2, 3));
System.out.println("add(\"Hello\", \"World\") = " + add("Hello", "World"));
// 调用不同版本的calculate方法
System.out.println("\n=== 计算方法重载 ===");
System.out.println("calculate(10, 5) = " + calculate(10, 5));
System.out.println("calculate(10, 5, '+') = " + calculate(10, 5, '+'));
System.out.println("calculate(10, 5, '-') = " + calculate(10, 5, '-'));
System.out.println("calculate(10, 5, '*') = " + calculate(10, 5, '*'));
System.out.println("calculate(10, 5, '/') = " + calculate(10, 5, '/'));
// 数组处理方法重载
System.out.println("\n=== 数组处理方法重载 ===");
int[] intArray = {1, 2, 3, 4, 5};
double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5};
String[] stringArray = {"apple", "banana", "cherry"};
System.out.println("int数组和: " + sum(intArray));
System.out.println("double数组和: " + sum(doubleArray));
System.out.println("字符串数组连接: " + sum(stringArray));
}
// 打印方法重载 - 不同参数类型
public static void print(String message) {
System.out.println("字符串: " + message);
}
public static void print(int number) {
System.out.println("整数: " + number);
}
public static void print(double number) {
System.out.println("浮点数: " + number);
}
public static void print(boolean value) {
System.out.println("布尔值: " + value);
}
// 加法方法重载 - 不同参数类型和数量
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
public static int add(int a, int b, int c) {
return a + b + c;
}
public static String add(String a, String b) {
return a + b;
}
// 计算方法重载 - 不同参数数量
public static int calculate(int a, int b) {
return a + b; // 默认执行加法
}
public static int calculate(int a, int b, char operator) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b != 0) {
return a / b;
} else {
throw new ArithmeticException("除数不能为零");
}
default:
throw new IllegalArgumentException("不支持的运算符: " + operator);
}
}
// 数组求和方法重载 - 不同数组类型
public static int sum(int[] array) {
int total = 0;
for (int num : array) {
total += num;
}
return total;
}
public static double sum(double[] array) {
double total = 0.0;
for (double num : array) {
total += num;
}
return total;
}
public static String sum(String[] array) {
StringBuilder result = new StringBuilder();
for (String str : array) {
result.append(str);
}
return result.toString();
}
}
3.7 本章小结
本章详细介绍了Java的基本语法,包括:
核心概念
- 程序结构:包声明、导入语句、类定义、方法定义
- 语法规则:大小写敏感、标识符命名、语句结束符、代码块
- 注释类型:单行注释、多行注释、文档注释
数据类型系统
- 基本数据类型:byte、short、int、long、float、double、char、boolean
- 引用数据类型:String、数组、对象
- 类型转换:自动转换、强制转换、精度丢失、溢出处理
运算符体系
- 算术运算符:+、-、*、/、%、++、–
- 关系运算符:==、!=、<、>、<=、>=
- 逻辑运算符:&&、||、!、短路求值
- 位运算符:&、|、^、~、<<、>>、>>>
控制结构
- 条件语句:if、if-else、if-else if-else、switch、三元运算符
- 循环语句:for、while、do-while、增强for循环
- 跳转语句:break、continue、标签跳转
数组操作
- 一维数组:声明、初始化、访问、遍历、排序、复制
- 多维数组:二维数组、锯齿数组、三维数组、矩阵运算
方法基础
- 方法定义:访问修饰符、返回类型、方法名、参数列表
- 方法调用:参数传递、返回值处理
- 方法重载:不同参数类型、不同参数数量
编程最佳实践
- 命名规范:驼峰命名法、常量命名、有意义的变量名
- 代码组织:适当的缩进、合理的注释、方法职责单一
- 错误处理:边界检查、异常处理、输入验证
下一章预告
第4章将深入学习面向对象编程基础,包括: - 类和对象的概念 - 构造方法和析构方法 - 封装、继承、多态 - 访问修饰符 - static关键字 - this和super关键字
练习题
基础练习
- 编写程序计算圆的面积和周长
- 实现一个简单的计算器(支持四则运算)
- 编写程序判断一个年份是否为闰年
- 实现冒泡排序算法
- 编写程序找出数组中的最大值和最小值
进阶练习
- 实现矩阵乘法运算
- 编写程序生成斐波那契数列
- 实现二分查找算法
- 编写程序统计字符串中各字符的出现次数
- 实现一个简单的学生成绩管理系统(使用数组)
挑战练习
- 编写程序解决汉诺塔问题
- 实现快速排序算法
- 编写程序生成杨辉三角
- 实现一个简单的文本处理器(统计单词、行数等)
- 编写程序模拟简单的银行账户操作