Java 类与对象实践:从代码验证到四则运算开发
Java类与对象实践:从代码验证到四则运算开发
在学习Java类与对象后,通过代码验证课件知识点、完成四则运算开发,能更深入理解面向对象编程思想。以下是我在实践过程中的详细记录,包含知识点验证、问题解决及项目开发过程。
一、课件代码验证与知识点总结
(一)引用类型与原始数据类型差异验证
- 验证代码
public class TypeTest {
public static void main(String[] args) {
// 原始数据类型变量定义
int value = 100;
// 引用类型变量定义(未引用对象时为null)
MyClass obj = null;
// 为引用类型变量创建对象
obj = new MyClass();
System.out.println("原始数据类型值:" + value);
System.out.println("引用类型对象字段值:" + obj.getValue());
}
}
class MyClass {
private int value = 200;
public int getValue() {
return value;
}
}
- 验证结果:原始数据类型定义时直接分配内存并赋值;引用类型变量初始为null,仅当通过new创建对象后,才指向实际内存空间。
- 核心结论:引用类型变量存储对象地址,原始数据类型变量直接存储数据值。
(二)对象判等:==与equals()方法对比
- 验证代码
public class EqualsTest {
public static void main(String[] args) {
MyTestClass obj1 = new MyTestClass(100);
MyTestClass obj2 = new MyTestClass(100);
MyTestClass obj3 = obj1;
// 使用==判等
System.out.println("obj1 == obj2:" + (obj1 == obj2)); // false
System.out.println("obj1 == obj3:" + (obj1 == obj3)); // true
// 使用重写后的equals()判等
System.out.println("obj1.equals(obj2):" + obj1.equals(obj2)); // true
}
}
class MyTestClass {
public int value;
public MyTestClass(int initValue) {
value = initValue;
}
// 重写equals()方法
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyTestClass that = (MyTestClass) obj;
return value == that.value;
}
}
- 验证结果:==对引用类型比较地址,对原始数据类型比较值;重写后的equals()可实现对象内容(字段值)比较。
- 注意事项:实际开发中重写equals()需添加参数有效性检测,如判断obj是否为null、是否为同一类实例。
(三)类字段初始化顺序验证
- 验证代码
public class InitializeOrderTest {
public static void main(String[] args) {
InitializeBlockClass obj1 = new InitializeBlockClass();
System.out.println("无参构造创建对象的field值:" + obj1.field); // 100
InitializeBlockClass obj2 = new InitializeBlockClass(300);
System.out.println("有参构造创建对象的field值:" + obj2.field); // 300
}
}
class InitializeBlockClass {
// 字段初始值
public int field = 200;
// 初始化块
{
field = 100;
}
// 无参构造
public InitializeBlockClass() {}
// 有参构造
public InitializeBlockClass(int value) {
this.field = value;
}
}
- 验证结果:初始化顺序为“字段默认值/初始化块(按代码顺序)→ 构造函数”,构造函数赋值最终生效。
- 开发建议:实际项目中应保证一个字段仅初始化一次,避免逻辑混乱。
(四)静态成员与静态初始化块验证
- 验证代码
public class StaticTest {
public static void main(String[] args) {
Employee emp1 = new Employee("张三");
Employee emp2 = new Employee("李四");
// 通过类名访问静态字段
System.out.println("总员工数(类名访问):" + Employee.totalEmployees); // 2
// 静态方法调用
Employee.clearTotal();
System.out.println("清空后总员工数:" + Employee.totalEmployees); // 0
}
}
class Employee {
String name;
// 静态字段
static int totalEmployees;
// 静态初始化块
static {
totalEmployees = 0;
System.out.println("静态初始化块执行");
}
public Employee(String name) {
this.name = name;
totalEmployees++;
}
// 静态方法
static void clearTotal() {
totalEmployees = 0;
}
}
- 验证结果:静态初始化块仅执行一次;静态成员可通过类名或对象名访问,推荐使用类名;静态方法只能访问静态成员。
二、四则运算项目开发过程
(一)阶段1:基础版——生成30道小学四则运算题
- 功能需求:随机生成30道整数四则运算题(含加减乘除,结果非负),避免除数为0。
- 核心代码
import java.util.Random;
public class ArithmeticGenerator {
public static void main(String[] args) {
Random random = new Random();
// 生成30道题
for (int i = 1; i <= 30; i++) {
// 随机生成两个1-100的整数
int num1 = random.nextInt(100) + 1;
int num2 = random.nextInt(100) + 1;
// 随机选择运算符(0:加,1:减,2:乘,3:除)
int op = random.nextInt(4);
String operator = getOperator(op);
// 确保减法结果非负、除法除数非0且结果整数
while (!isValid(num1, num2, op)) {
num1 = random.nextInt(100) + 1;
num2 = random.nextInt(100) + 1;
}
System.out.printf("第%d题:%d %s %d = \n", i, num1, operator, num2);
}
}
// 获取运算符字符串
private static String getOperator(int op) {
return switch (op) {
case 0 -> "+";
case 1 -> "-";
case 2 -> "*";
case 3 -> "/";
default -> "+";
};
}
// 验证题目有效性
private static boolean isValid(int num1, int num2, int op) {
if (op == 1) { // 减法
return num1 >= num2;
} else if (op == 3) { // 除法
return num2 != 0 && num1 % num2 == 0;
}
return true;
}
}
- 运行效果:控制台依次输出30道符合要求的四则运算题,无无效题目(如负数结果、除数为0)。
(二)阶段2:进阶版——题目去重与可定制
- 新增功能:支持自定义题目数量、打印方式(控制台/文本文件),并实现题目去重。
- 核心优化点
- 题目去重:将每道题转换为字符串(如“5+3”),存入HashSet,利用集合不可重复性实现去重。
- 文本文件输出:使用BufferedWriter将题目写入本地文本文件,三题一行排版。
- 关键代码(去重与文件输出)
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class CustomArithmeticGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 自定义题目数量
System.out.print("请输入题目数量:");
int count = scanner.nextInt();
// 自定义打印方式
System.out.print("请选择打印方式(1:控制台,2:文本文件):");
int printType = scanner.nextInt();
Set<String> questionSet = new HashSet<>();
Random random = new Random();
BufferedWriter writer = null;
try {
if (printType == 2) {
writer = new BufferedWriter(new FileWriter("arithmetic_questions.txt"));
}
// 生成不重复题目
while (questionSet.size() < count) {
int num1 = random.nextInt(100) + 1;
int num2 = random.nextInt(100) + 1;
int op = random.nextInt(4);
String operator = getOperator(op);
if (isValid(num1, num2, op)) {
String question = num1 + " " + operator + " " + num2 + " = ";
if (!questionSet.contains(question)) {
questionSet.add(question);
// 按打印方式输出
if (printType == 1) {
System.out.print(question + "\t");
// 控制台每三题换行
if (questionSet.size() % 3 == 0) {
System.out.println();
}
} else {
writer.write(question);
writer.write("\t");
if (questionSet.size() % 3 == 0) {
writer.newLine();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
scanner.close();
}
System.out.println("\n题目生成完成!");
}
// 复用getOperator与isValid方法,同阶段1
}
- 运行效果:输入题目数量(如50)和打印方式(如2)后,本地生成arithmetic_questions.txt文件,文件内三题一行,无重复题目。
(三)阶段3:高级版——答题交互、错题本与数据库连接
- 新增功能
- 答题交互:用户输入答案,实时判断正误,记录答题时间与错题。
- 错题本与正确率统计:答题结束后显示正确率,支持查看错题并二次答题。
- 文本导入判题:读取阶段2生成的文本文件,批量判题并输出统计结果。
- 数据库连接:使用JDBC连接MySQL,将题目、答题记录存入数据库(需提前创建表)。
- 核心代码片段(答题交互与错题本)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ArithmeticQuiz {
// 错题实体类
static class WrongQuestion {
String question;
int userAnswer;
int correctAnswer;
public WrongQuestion(String question, int userAnswer, int correctAnswer) {
this.question = question;
this.userAnswer = userAnswer;
this.correctAnswer = correctAnswer;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 假设从阶段2获取题目列表(此处简化为示例题目)
List<String> questions = new ArrayList<>();
List<Integer> correctAnswers = new ArrayList<>();
// 添加示例题目与正确答案
questions.add("5 + 3 = ");
correctAnswers.add(8);
questions.add("10 - 4 = ");
correctAnswers.add(6);
questions.add("6 * 7 = ");
correctAnswers.add(42);
List<WrongQuestion> wrongQuestions = new ArrayList<>();
int correctCount = 0;
long startTime = System.currentTimeMillis();
// 答题过程
for (int i = 0; i < questions.size(); i++) {
System.out.print("请回答第" + (i + 1) + "题:" + questions.get(i));
int userAnswer = scanner.nextInt();
int correct = correctAnswers.get(i);
if (userAnswer == correct) {
correctCount++;
System.out.println("回答正确!");
} else {
System.out.println("回答错误,正确答案是:" + correct);
wrongQuestions.add(new WrongQuestion(questions.get(i), userAnswer, correct));
}
}
// 答题统计
long endTime = System.currentTimeMillis();
double accuracy = (double) correctCount / questions.size() * 100;
System.out.printf("\n答题结束!用时:%d秒,正确率:%.2f%%\n",
(endTime - startTime) / 1000, accuracy);
// 错题本功能
if (!wrongQuestions.isEmpty()) {
System.out.print("是否查看错题本并二次答题?(1:是,2:否):");
int choice = scanner.nextInt();
if (choice == 1) {
int retryCorrect = 0;
for (WrongQuestion wq : wrongQuestions) {
System.out.print("二次答题:" + wq.question);
int retryAnswer = scanner.nextInt();
if (retryAnswer == wq.correctAnswer) {
retryCorrect++;
System.out.println("回答正确!");
} else {
System.out.println("仍错误,正确答案是:" + wq.correctAnswer);
}
}
System.out.printf("二次答题正确率:%.2f%%\n",
(double) retryCorrect / wrongQuestions.size() * 100);
}
}
scanner.close();
}
}
- 数据库连接说明:需导入MySQL驱动包(如mysql-connector-java-8.0.30.jar),创建arithmetic_questions(存储题目)和answer_records(存储答题记录)表,通过JDBC实现数据插入与查询。
三、实践总结与收获
- 知识点巩固:通过代码验证,深入理解了引用类型、对象判等、初始化顺序、静态成员等核心概念,纠正了“equals()默认比较地址”“静态方法可访问实例成员”等误区。
- 开发能力提升:从基础功能到高级交互,逐步掌握了需求分析、逻辑设计、代码优化(如去重、文件操作)的流程,学会了使用集合、IO流、JDBC等技术解决实际问题。
- 问题解决思路:面对“题目去重”“无效题目过滤”等问题,通过查阅资料、调试代码,学会了利用HashSet特性、添加有效性校验等解决方案,培养了debug能力。
需要的话,我可以帮你整理一份四则运算项目完整代码包,包含各阶段源码、数据库建表语句和使用说明,方便你直接运行和补充到博客中。

浙公网安备 33010602011771号