🧾 模拟试题(第一套)
一、简答题(共6题,每题5分,共30分)
- 简述面向对象编程的三个基本特征,并简要说明每个特征的含义。
- 什么是方法重载(Overload)和方法重写(Override)?请说明它们的区别。
- 简述
final关键字在类、方法和变量中的作用。 - 什么是 Lambda 表达式?请写出一个简单的 Lambda 表达式示例。
- 简述
try-catch-finally语句的执行流程。 - 什么是多线程?请列出 Java 中实现多线程的两种方式。
二、程序分析及填空题(共4题,每题10分,共40分)
题目1:数组遍历与排序
public class ArrayTest {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
// 填空:使用冒泡排序对数组进行升序排序
for (int i = __________; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (__________) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 遍历输出排序后的数组
for (int num : arr) {
System.out.print(num + " ");
}
}
}题目2:类的定义与继承
class Animal {
public void sound() {
System.out.println("动物叫");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("汪汪");
}
}
public class Test {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // 输出:__________
}
}题目3:异常处理
public class ExceptionTest {
public static void main(String[] args) {
try {
int[] arr = new int[5];
System.out.println(arr[10]);
} catch (__________ e) {
System.out.println("捕获数组越界异常");
} finally {
System.out.println("执行 finally 块");
}
}
}题目4:集合与泛型
import java.util.*;
public class CollectionTest {
public static void main(String[] args) {
List<String> list = new __________<>();
list.add("Java");
list.add("Python");
// 使用增强 for 循环遍历并输出
for (String s : __________) {
System.out.println(s);
}
}
}三、综合编程题(共2题,第1题20分,第2题10分,共30分)
题目1:图形界面编程(20分)
编写一个图形界面程序,包含以下组件:
- 一个标签(JLabel),显示“请输入姓名:”
- 一个文本框(JTextField)
- 一个按钮(JButton),点击后弹出一个对话框显示“你好,[姓名]!”
要求使用 JFrame、JLabel、JTextField、JButton 和 ActionListener。
题目2:多线程编程(10分)
使用 Runnable 接口实现一个多线程程序,创建两个线程,分别打印 1~5 的数字,每次打印间隔 1 秒。
✅ 参考答案
一、简答题答案
封装:隐藏对象的属性和实现细节,仅对外提供公共访问方式。
继承:子类继承父类的属性和方法,实现代码复用。
多态:同一操作作用于不同对象,可以有不同的解释和表现。重载:同一类中方法名相同,参数列表不同。
重写:子类重新定义父类中已有的方法,方法签名相同。
区别:重载是编译时多态,重写是运行时多态。final类:不能被继承;final方法:不能被重写;final变量:常量,值不能改变。Lambda 表达式是匿名函数,用于简化函数式接口的实现。
示例:(a, b) -> a + b先执行
try块,若发生异常则跳转到匹配的catch块,最后无论是否异常都执行finally块。多线程是指一个程序中同时运行多个线程。
实现方式:继承Thread类、实现Runnable接口。
二、程序分析及填空题答案
题目1:
for (int i = arr.length - 1; i > 0; i--) {
if (arr[j] > arr[j + 1]) {题目2:
输出:汪汪
题目3:
catch (ArrayIndexOutOfBoundsException e) {题目4:
List<String> list = new ArrayList<>();
for (String s : list) {三、综合编程题答案
题目1:图形界面程序
import javax.swing.*;
import java.awt.event.*;
public class GreetingApp {
public static void main(String[] args) {
JFrame frame = new JFrame("问候程序");
JLabel label = new JLabel("请输入姓名:");
JTextField textField = new JTextField(10);
JButton button = new JButton("确认");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = textField.getText();
JOptionPane.showMessageDialog(frame, "你好," + name + "!");
}
});
JPanel panel = new JPanel();
panel.add(label);
panel.add(textField);
panel.add(button);
frame.add(panel);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}题目2:多线程程序
public class MultiThreadExample {
public static void main(String[] args) {
Runnable task = () -> {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t1 = new Thread(task, "线程1");
Thread t2 = new Thread(task, "线程2");
t1.start();
t2.start();
}
}🧾 模拟试题(第二套)
一、简答题(共5题,每题8分,共40分)
- 简述 Java 语言的特点。
- 简述 Java 程序的执行过程(从源码到运行)。
- 什么是单例设计模式?请写出一种实现方式。
- 抽象类与接口有什么区别?(至少三点)
- 简述流的分类(按数据流动方向、处理单位、功能)。
二、程序分析及补全题(共3题,每题10分,共30分)
题目1:异常处理
public class ExceptionDemo {
public static void main(String[] args) {
try {
int[] arr = new int[3];
System.out.println(arr[5]);
} catch (__________ e) {
System.out.println("数组越界异常");
} finally {
System.out.println("执行 finally 块");
}
}
}题目2:集合与泛型
import java.util.*;
public class CollectionDemo {
public static void main(String[] args) {
List<Integer> list = new __________<>();
list.add(3);
list.add(1);
list.add(2);
// 使用 Collections 对 list 进行排序
__________.sort(list);
// 遍历输出
for (Integer num : list) {
System.out.print(num + " ");
}
}
}题目3:图形界面事件处理
import javax.swing.*;
import java.awt.event.*;
public class ButtonDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("测试");
JButton btn = new JButton("点击");
// 使用 Lambda 表达式为按钮添加点击事件
btn.addActionListener(__________ -> {
JOptionPane.showMessageDialog(frame, "按钮被点击!");
});
frame.add(btn);
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}三、编程题(共2题,每题15分,共30分)
题目1:多线程编程(15分)
使用 Runnable 接口 实现两个线程,分别打印 1~10 的奇数和偶数,要求交替打印,并保证输出顺序正确(先奇后偶)。
题目2:图形界面编程(15分)
编写一个图形界面程序,包含以下组件:
- 一个标签:显示“请输入一个数字:”
- 一个文本框:用于输入数字
- 一个按钮:点击后判断输入的数字是否为素数,并在对话框中显示结果
要求使用 JFrame、JLabel、JTextField、JButton 和 ActionListener。
✅ 参考答案
一、简答题答案
- Java 语言特点:简单性、面向对象、平台无关性、安全性、多线程、动态性。
- 执行过程:
- 编写
.java源码 - 编译生成
.class字节码 - JVM 解释执行字节码
- 编写
- 单例模式:确保一个类只有一个实例,并提供全局访问点。
示例代码:javapublic class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } - 抽象类 vs 接口:
- 抽象类可以有构造方法,接口不能
- 抽象类可以有成员变量,接口只能有常量
- 类只能继承一个抽象类,但可以实现多个接口
- 流的分类:
- 按方向:输入流、输出流
- 按单位:字节流、字符流
- 按功能:节点流、处理流(过滤流)
二、程序分析及补全题答案
题目1:
catch (ArrayIndexOutOfBoundsException e) {题目2:
List<Integer> list = new ArrayList<>();
Collections.sort(list);题目3:
btn.addActionListener(e -> {三、编程题答案
题目1:多线程编程
public class OddEvenPrinter {
private static final Object lock = new Object();
private static int number = 1;
private static final int MAX = 10;
public static void main(String[] args) {
Runnable oddTask = () -> {
synchronized (lock) {
while (number <= MAX) {
if (number % 2 == 1) {
System.out.println(Thread.currentThread().getName() + ": " + number);
number++;
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Runnable evenTask = () -> {
synchronized (lock) {
while (number <= MAX) {
if (number % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + number);
number++;
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Thread t1 = new Thread(oddTask, "奇数线程");
Thread t2 = new Thread(evenTask, "偶数线程");
t1.start();
t2.start();
}
}题目2:图形界面编程
import javax.swing.*;
import java.awt.event.*;
public class PrimeChecker {
public static void main(String[] args) {
JFrame frame = new JFrame("素数判断");
JLabel label = new JLabel("请输入一个数字:");
JTextField textField = new JTextField(10);
JButton button = new JButton("判断");
button.addActionListener(e -> {
try {
int num = Integer.parseInt(textField.getText());
boolean isPrime = isPrime(num);
JOptionPane.showMessageDialog(frame, isPrime ? "是素数" : "不是素数");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "请输入有效数字");
}
});
JPanel panel = new JPanel();
panel.add(label);
panel.add(textField);
panel.add(button);
frame.add(panel);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
}模拟试题(第三套)
一、简答题(共5题,每题8分,共40分)
- 简述 Java 中
final关键字在类、方法和变量中的作用。 - 什么是运行时异常(Runtime Exception)和受检查异常(Checked Exception)?请各举两个例子。
- 简述线程的互斥与协作是如何实现的,并说明
synchronized、wait()和notify()的作用。 - Java 集合框架中,Set、List 和 Map 有什么区别?请简要说明它们的特点和常用实现类。
- 什么是 Lambda 表达式?请写出一个使用 Lambda 表达式实现
Runnable接口的示例。
二、程序分析及补全题(共3题,每题10分,共30分)
题目1:IO 流操作
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("source.txt");
__________ fos = new FileOutputStream("target.txt");
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
__________;
}
fis.close();
fos.close();
System.out.println("文件复制完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}题目2:集合排序
import java.util.*;
class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() { return name; }
public int getScore() { return score; }
public String toString() {
return name + ":" + score;
}
}
public class StudentSort {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 85));
students.add(new Student("李四", 92));
students.add(new Student("王五", 78));
// 按分数从高到低排序
Collections.sort(students, __________);
for (Student s : students) {
System.out.println(s);
}
}
}题目3:异常处理
public class ExceptionDemo {
public static void validateAge(int age) __________ {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("年龄不合法");
}
System.out.println("年龄验证通过: " + age);
}
public static void main(String[] args) {
try {
validateAge(200);
} __________ (IllegalArgumentException e) {
System.out.println("捕获异常: " + e.getMessage());
}
}
}三、编程题(共2题,每题15分,共30分)
题目1:集合操作(15分)
编写一个程序,实现以下功能:
- 使用
Map<String, Integer>存储学生姓名和成绩 - 添加至少5个学生的信息
- 计算所有学生的平均分
- 找出成绩最高的学生
- 使用
ArrayList存储不及格(成绩<60)的学生姓名
题目2:图形界面综合编程(15分)
编写一个简单的计算器界面,包含:
- 两个文本框用于输入数字
- 四个按钮分别对应加、减、乘、除运算
- 一个标签显示运算结果
- 一个"清空"按钮重置所有输入和结果
要求:
- 使用
GridLayout或FlowLayout进行布局 - 为按钮添加事件监听器
- 处理除零异常,出现异常时显示"计算错误"
参考答案
一、简答题答案
final关键字作用:final类:不能被继承final方法:不能被重写final变量:常量,值不能被修改
异常分类:
- 运行时异常:
NullPointerException、ArrayIndexOutOfBoundsException - 受检查异常:
IOException、ClassNotFoundException
- 运行时异常:
线程同步:
synchronized:实现互斥,确保同一时间只有一个线程访问共享资源wait():使线程等待并释放锁notify():唤醒等待的线程
集合框架:
Set:无序、不重复,如HashSet、TreeSetList:有序、可重复,如ArrayList、LinkedListMap:键值对,如HashMap、TreeMap
Lambda 表达式:
javaRunnable r = () -> System.out.println("Hello Lambda"); new Thread(r).start();
二、程序分析及补全题答案
题目1:
FileOutputStream fos = new FileOutputStream("target.txt");
fos.write(buffer, 0, length);题目2:
Collections.sort(students, (s1, s2) -> s2.getScore() - s1.getScore());题目3:
public static void validateAge(int age) throws IllegalArgumentException {
} catch (IllegalArgumentException e) {三、编程题答案
题目1:集合操作
import java.util.*;
public class StudentManager {
public static void main(String[] args) {
Map<String, Integer> students = new HashMap<>();
students.put("张三", 85);
students.put("李四", 92);
students.put("王五", 78);
students.put("赵六", 45);
students.put("钱七", 88);
// 计算平均分
int sum = 0;
for (int score : students.values()) {
sum += score;
}
double average = (double) sum / students.size();
System.out.println("平均分: " + average);
// 找出最高分
String topStudent = "";
int maxScore = -1;
for (Map.Entry<String, Integer> entry : students.entrySet()) {
if (entry.getValue() > maxScore) {
maxScore = entry.getValue();
topStudent = entry.getKey();
}
}
System.out.println("最高分学生: " + topStudent + ", 分数: " + maxScore);
// 不及格学生
List<String> failedStudents = new ArrayList<>();
for (Map.Entry<String, Integer> entry : students.entrySet()) {
if (entry.getValue() < 60) {
failedStudents.add(entry.getKey());
}
}
System.out.println("不及格学生: " + failedStudents);
}
}题目2:图形界面计算器
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleCalculator {
public static void main(String[] args) {
JFrame frame = new JFrame("简单计算器");
frame.setLayout(new FlowLayout());
JTextField num1Field = new JTextField(10);
JTextField num2Field = new JTextField(10);
JLabel resultLabel = new JLabel("结果: ");
JButton addBtn = new JButton("+");
JButton subBtn = new JButton("-");
JButton mulBtn = new JButton("*");
JButton divBtn = new JButton("/");
JButton clearBtn = new JButton("清空");
// 加法
addBtn.addActionListener(e -> {
try {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
resultLabel.setText("结果: " + (num1 + num2));
} catch (NumberFormatException ex) {
resultLabel.setText("输入错误");
}
});
// 减法
subBtn.addActionListener(e -> {
try {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
resultLabel.setText("结果: " + (num1 - num2));
} catch (NumberFormatException ex) {
resultLabel.setText("输入错误");
}
});
// 乘法
mulBtn.addActionListener(e -> {
try {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
resultLabel.setText("结果: " + (num1 * num2));
} catch (NumberFormatException ex) {
resultLabel.setText("输入错误");
}
});
// 除法
divBtn.addActionListener(e -> {
try {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
if (num2 == 0) {
resultLabel.setText("计算错误: 除零");
} else {
resultLabel.setText("结果: " + (num1 / num2));
}
} catch (NumberFormatException ex) {
resultLabel.setText("输入错误");
}
});
// 清空
clearBtn.addActionListener(e -> {
num1Field.setText("");
num2Field.setText("");
resultLabel.setText("结果: ");
});
frame.add(new JLabel("数字1:"));
frame.add(num1Field);
frame.add(new JLabel("数字2:"));
frame.add(num2Field);
frame.add(addBtn);
frame.add(subBtn);
frame.add(mulBtn);
frame.add(divBtn);
frame.add(clearBtn);
frame.add(resultLabel);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}模拟试题(第四套)
一、简答题(共5题,每题8分,共40分)
- 简述 Java 程序的执行过程(从源码到运行),并说明 JVM 的作用。
- 什么是单例设计模式?请写出一种线程安全的单例模式实现。
- 简述
final关键字在类、方法和变量中的作用,并说明使用final的好处。 - 什么是静态绑定和动态绑定?请举例说明它们在 Java 中的应用场景。
- 简述 Java 中流的分类(按数据流动方向、处理单位、功能),并各举两个例子。
二、程序分析及补全题(共3题,每题10分,共30分)
题目1:IO 流操作补全
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
// 创建文件输入流
__________ fis = new FileInputStream("source.txt");
// 创建缓冲输入流提高效率
__________ bis = new BufferedReader(fis);
// 创建文件输出流
FileOutputStream fos = new FileOutputStream("target.txt");
byte[] buffer = new byte[1024];
int length;
while ((length = __________) != -1) {
fos.write(buffer, 0, length);
}
// 关闭流
bis.close();
__________;
System.out.println("文件复制完成");
} catch (IOException e) {
System.out.println("文件操作错误: " + e.getMessage());
}
}
}题目2:异常处理分析
public class ExceptionAnalysis {
public static void main(String[] args) {
try {
int[] arr = new int[5];
System.out.println(arr[10]);
String str = null;
System.out.println(str.length());
} catch (__________ e) {
System.out.println("数组越界异常");
} catch (__________ e) {
System.out.println("空指针异常");
} finally {
System.out.println("finally块执行");
}
System.out.println("程序继续执行");
}
}题目3:集合操作补全
import java.util.*;
public class CollectionDemo {
public static void main(String[] args) {
// 创建List集合
__________<String> list = new __________<>();
list.add("Java");
list.add("Python");
list.add("C++");
list.add("JavaScript");
// 排序
__________.sort(list);
// 遍历输出
for (__________ item : list) {
System.out.println(item);
}
// 使用迭代器遍历
__________<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}三、编程题(共2题,每题15分,共30分)
题目1:多线程银行账户操作(15分)
编写一个多线程程序,模拟两个人同时操作一个银行账户:
- 创建一个
BankAccount类,包含账户余额和取款方法 - 使用
synchronized关键字保证线程安全 - 创建两个线程分别代表两个人,每人连续取款3次,每次取款金额随机
- 要求输出每次取款后的余额,确保数据一致性
题目2:图形界面学生信息管理系统(15分)
编写一个图形界面程序,实现学生信息管理功能:
- 使用
FlowLayout布局 - 包含以下组件:
- 文本框:学号、姓名、成绩
- 按钮:添加、删除、查询、清空
- 文本区域:显示所有学生信息
- 使用
ArrayList存储学生对象 - 实现功能:
- 添加学生信息到集合并显示
- 根据学号删除学生信息
- 根据学号查询学生信息
- 清空所有输入框
参考答案
一、简答题答案
Java程序执行过程:
- 编写
.java源文件 - 使用
javac编译生成.class字节码文件 - JVM 加载字节码文件并解释执行
- JVM作用:提供跨平台运行环境,管理内存,执行垃圾回收,确保安全性
- 编写
单例模式:
javapublic class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }final关键字:
final类:不能被继承final方法:不能被重写final变量:常量,值不能改变- 好处:提高性能、确保线程安全、防止意外修改
静态绑定与动态绑定:
- 静态绑定:编译时确定,如static方法、final方法、private方法
- 动态绑定:运行时确定,如普通实例方法的重写
- 示例:java
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog bark"); } } // 动态绑定:a.sound() 在运行时确定调用Dog的方法 Animal a = new Dog(); a.sound(); // 输出 "Dog bark"
流的分类:
- 按方向:输入流(
FileInputStream)、输出流(FileOutputStream) - 按单位:字节流(
InputStream)、字符流(Reader) - 按功能:节点流(
FileReader)、处理流(BufferedReader)
- 按方向:输入流(
二、程序分析及补全题答案
题目1:
FileInputStream fis = new FileInputStream("source.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
while ((length = bis.read(buffer)) != -1) {
fos.close();题目2:
catch (ArrayIndexOutOfBoundsException e) {
catch (NullPointerException e) {题目3:
List<String> list = new ArrayList<>();
Collections.sort(list);
for (String item : list) {
Iterator<String> iterator = list.iterator();三、编程题答案
题目1:多线程银行账户操作
class BankAccount {
private int balance;
public BankAccount(int initialBalance) {
this.balance = initialBalance;
}
public synchronized void withdraw(int amount, String person) {
if (balance >= amount) {
balance -= amount;
System.out.println(person + " 取款 " + amount + "元,余额: " + balance);
} else {
System.out.println(person + " 取款失败,余额不足");
}
}
public int getBalance() {
return balance;
}
}
public class BankDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
Runnable person1 = () -> {
for (int i = 0; i < 3; i++) {
int amount = (int)(Math.random() * 200) + 50;
account.withdraw(amount, "张三");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable person2 = () -> {
for (int i = 0; i < 3; i++) {
int amount = (int)(Math.random() * 200) + 50;
account.withdraw(amount, "李四");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t1 = new Thread(person1,"name");
Thread t2 = new Thread(person2);
t1.start();
t2.start();
}
}题目2:图形界面学生信息管理系统
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Student {
private String id;
private String name;
private int score;
public Student(String id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
public String getId() { return id; }
public String getName() { return name; }
public int getScore() { return score; }
@Override
public String toString() {
return "学号: " + id + ", 姓名: " + name + ", 成绩: " + score;
}
}
public class StudentManagementSystem {
private static ArrayList<Student> students = new ArrayList<>();
public static void main(String[] args) {
JFrame frame = new JFrame("学生信息管理系统");
frame.setLayout(new FlowLayout());
// 输入组件
JLabel idLabel = new JLabel("学号:");
JTextField idField = new JTextField(10);
JLabel nameLabel = new JLabel("姓名:");
JTextField nameField = new JTextField(10);
JLabel scoreLabel = new JLabel("成绩:");
JTextField scoreField = new JTextField(10);
// 按钮
JButton addBtn = new JButton("添加");
JButton deleteBtn = new JButton("删除");
JButton searchBtn = new JButton("查询");
JButton clearBtn = new JButton("清空");
// 显示区域
JTextArea displayArea = new JTextArea(10, 30);
displayArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(displayArea);
// 添加组件
frame.add(idLabel);
frame.add(idField);
frame.add(nameLabel);
frame.add(nameField);
frame.add(scoreLabel);
frame.add(scoreField);
frame.add(addBtn);
frame.add(deleteBtn);
frame.add(searchBtn);
frame.add(clearBtn);
frame.add(scrollPane);
// 添加按钮事件
addBtn.addActionListener(e -> {
try {
String id = idField.getText();
String name = nameField.getText();
int score = Integer.parseInt(scoreField.getText());
students.add(new Student(id, name, score));
updateDisplay(displayArea);
clearFields(idField, nameField, scoreField);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "请输入有效的成绩数字");
}
});
deleteBtn.addActionListener(e -> {
String id = idField.getText();
students.removeIf(student -> student.getId().equals(id));
updateDisplay(displayArea);
clearFields(idField, nameField, scoreField);
});
searchBtn.addActionListener(e -> {
String id = idField.getText();
for (Student student : students) {
if (student.getId().equals(id)) {
displayArea.setText(student.toString());
return;
}
}
displayArea.setText("未找到该学号的学生");
});
clearBtn.addActionListener(e -> {
clearFields(idField, nameField, scoreField);
displayArea.setText("");
});
frame.setSize(400, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void updateDisplay(JTextArea displayArea) {
StringBuilder sb = new StringBuilder();
for (Student student : students) {
sb.append(student.toString()).append("\n");
}
displayArea.setText(sb.toString());
}
private static void clearFields(JTextField... fields) {
for (JTextField field : fields) {
field.setText("");
}
}
}Java语言模拟试题(第五套)
一、简答题(共5题,每题8分,共40分)
- 简述 Java 语言的特点,并说明平台无关性是如何实现的。
- 什么是抽象类?抽象类与普通类有什么区别?抽象类与接口的主要区别是什么?
- 简述 Java 中异常处理的两种机制(throws 和 try-catch-finally),并说明它们的使用场景。
- 什么是线程的互斥与协作?请说明 synchronized、wait() 和 notify() 方法在其中的作用。
- 简述 Java 集合框架中 List、Set 和 Map 的区别,并各举一个常用实现类。
二、程序分析及补全题(共3题,每题10分,共30分)
题目1:多线程同步补全
class SharedResource {
private int count = 0;
public __________ void increment() {
count++;
}
public void printCount() {
System.out.println("Count: " + count);
}
}
public class ThreadSyncDemo {
public static void main(String[] args) __________ InterruptedException {
SharedResource resource = new SharedResource();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
resource.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
resource.increment();
}
});
t1.start();
__________;
t1.join();
t2.join();
resource.printCount(); // 应该输出2000
}
}题目2:泛型与集合补全
import java.util.*;
class Student __________ Comparable<Student> {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() { return name; }
public int getScore() { return score; }
@Override
public int compareTo(Student other) {
return __________ - other.score;
}
@Override
public String toString() {
return name + ":" + score;
}
}
public class GenericCollectionDemo {
public static void main(String[] args) {
__________<Student> students = new __________<>();
students.add(new Student("张三", 85));
students.add(new Student("李四", 92));
students.add(new Student("王五", 78));
// 排序
__________.sort(students);
// 遍历输出
for (Student s : students) {
System.out.println(s);
}
}
}题目3:IO流操作补全
import java.io.*;
import java.util.*;
public class FileOperation {
public static void main(String[] args) {
try {
// 写入数据到文件
__________ dos = new DataOutputStream(
new FileOutputStream("data.dat"));
dos.writeInt(100);
dos.writeDouble(3.14);
dos.writeUTF("Hello World");
dos.close();
// 从文件读取数据
__________ dis = new DataInputStream(
new FileInputStream("data.dat"));
int num = dis.readInt();
double value = dis.readDouble();
String text = dis.readUTF();
dis.close();
System.out.println("读取的数据: " + num + ", " + value + ", " + text);
} catch (__________ e) {
System.out.println("文件操作错误: " + e.getMessage());
}
}
}三、编程题(共2题,每题15分,共30分)
题目1:生产者-消费者模型(15分)
使用多线程实现生产者-消费者模型:
- 创建一个共享的缓冲区(使用
ArrayList),最大容量为5 - 生产者线程每隔1秒生产一个随机数字(1-100)放入缓冲区
- 消费者线程每隔2秒从缓冲区取出一个数字并显示
- 使用
synchronized、wait()和notifyAll()实现线程同步 - 当缓冲区满时生产者等待,缓冲区空时消费者等待
题目2:图形界面计算器(15分)
编写一个图形界面计算器,实现以下功能:
- 使用
GridLayout布局 - 包含数字按钮(0-9)和运算符按钮(+、-、×、÷、=、C)
- 一个文本框用于显示输入和结果
- 实现基本的四则运算功能
- 处理除零异常,出现异常时显示"错误"
- 点击"C"按钮清空所有输入
参考答案
一、简答题答案
Java语言特点:
- 简单性、面向对象、平台无关性、安全性、多线程、动态性
- 平台无关性实现:通过JVM(Java虚拟机),Java源码编译成字节码,字节码在JVM上运行,JVM针对不同平台有不同的实现
抽象类:
- 抽象类是不能被实例化的类,可以包含抽象方法和具体方法
- 与普通类区别:抽象类不能被实例化,可以包含抽象方法
- 与接口区别:抽象类可以有构造器、成员变量,单继承;接口只有常量,多重实现
异常处理机制:
- throws:声明方法可能抛出的异常,让调用者处理
- try-catch-finally:捕获并处理异常
- 使用场景:throws用于不想在当前方法处理异常时;try-catch用于需要立即处理异常时
线程互斥与协作:
- 互斥:保证同一时间只有一个线程访问共享资源,使用
synchronized - 协作:线程间协调工作,使用
wait()使线程等待,notify()唤醒等待线程
- 互斥:保证同一时间只有一个线程访问共享资源,使用
集合框架区别:
- List:有序、可重复,如
ArrayList - Set:无序、不重复,如
HashSet - Map:键值对,如
HashMap
- List:有序、可重复,如
二、程序分析及补全题答案
题目1:
public synchronized void increment() {
public static void main(String[] args) throws InterruptedException {
t2.start();题目2:
class Student implements Comparable<Student> {
return other.score - this.score; // 按分数降序排列
List<Student> students = new ArrayList<>();
Collections.sort(students);题目3:
DataOutputStream dos = new DataOutputStream(
DataInputStream dis = new DataInputStream(
catch (IOException e) {三、编程题答案
题目1:生产者-消费者模型
import java.util.*;
class Buffer {
private final List<Integer> list = new ArrayList<>();
private final int MAX_SIZE = 5;
public synchronized void produce(int value) throws InterruptedException {
while (list.size() == MAX_SIZE) {
wait(); // 缓冲区满,等待
}
list.add(value);
System.out.println("生产: " + value + ", 缓冲区大小: " + list.size());
notifyAll(); // 通知消费者
}
public synchronized int consume() throws InterruptedException {
while (list.isEmpty()) {
wait(); // 缓冲区空,等待
}
int value = list.remove(0);
System.out.println("消费: " + value + ", 缓冲区大小: " + list.size());
notifyAll(); // 通知生产者
return value;
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
Buffer buffer = new Buffer();
// 生产者线程
Thread producer = new Thread(() -> {
try {
Random random = new Random();
while (true) {
int value = random.nextInt(100) + 1;
buffer.produce(value);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// 消费者线程
Thread consumer = new Thread(() -> {
try {
while (true) {
buffer.consume();
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producer.start();
consumer.start();
}
}题目2:图形界面计算器
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator {
private JFrame frame;
private JTextField display;
private String currentInput = "";
private double result = 0;
private String operator = "=";
private boolean calculating = true;
public static void main(String[] args) {
new Calculator();
}
public Calculator() {
frame = new JFrame("计算器");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
display = new JTextField("0");
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setFont(new Font("Arial", Font.BOLD, 20));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "×",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.BOLD, 18));
button.addActionListener(new ButtonClickListener());
buttonPanel.add(button);
}
frame.add(display, BorderLayout.NORTH);
frame.add(buttonPanel, BorderLayout.CENTER);
frame.setSize(300, 400);
frame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ('0' <= command.charAt(0) && command.charAt(0) <= '9') {
if (calculating) {
currentInput = command;
} else {
currentInput += command;
}
calculating = false;
display.setText(currentInput);
} else if (command.equals("C")) {
currentInput = "0";
result = 0;
operator = "=";
calculating = true;
display.setText(currentInput);
} else {
if (calculating) {
operator = command;
} else {
double x = Double.parseDouble(currentInput);
calculate(x);
operator = command;
currentInput = String.valueOf(result);
display.setText(currentInput);
calculating = true;
}
}
}
private void calculate(double x) {
switch (operator) {
case "+":
result += x;
break;
case "-":
result -= x;
break;
case "×":
result *= x;
break;
case "/":
if (x == 0) {
display.setText("错误");
currentInput = "0";
result = 0;
operator = "=";
calculating = true;
return;
}
result /= x;
break;
case "=":
result = x;
break;
}
}
}
}