Java高级编程知识总结
程序员文章站
2024-02-09 17:49:04
Java高级编程知识总结及复习(三)1、异常处理try-catch-finally异常捕获处理机制public class Demo101 { public static void main(String[] args) { int x = 10; int y = 0; try{ System.out.println(x / y); }catch (ArithmeticException e){...
Java高级编程知识总结及复习(三)
1、异常处理
try-catch-finally异常捕获处理机制
public class Demo101 {
public static void main(String[] args) {
int x = 10;
int y = 0;
try{
System.out.println(x / y);
}catch (ArithmeticException e){
System.out.println("处理被除数为0的异常");
e.printStackTrace();
}catch (Exception e){
System.out.println("处理其他异常");
e.printStackTrace();
}finally {
System.out.println("一定会执行的部分");
}
System.out.println("异常处理成功");
}
}
处理被除数为0的异常
java.lang.ArithmeticException: / by zero
at Demo101.main(Demo101.java:6)
一定会执行的部分
异常处理成功
throws声明抛出异常处理机制
class MyMath02 {
// 异常交给调用处处理,使用throws
public static int div(int x, int y) throws Exception {
int temp = 0;
System.out.println("开始");
try {
temp = x / y;
} catch (Exception e) {
// 向上抛异常对象
throw e;
} finally {
System.out.println("结束");
}
return temp;
}
}
public class Demo04 {
public static void main(String[] args) {
try {
System.out.println(MyMath02.div(10, 0));
} catch (Exception e) {
e.printStackTrace();
}
}
}
自定义异常
//自定义异常类必须继承Exception或RuntimeException类。
class BombException extends RuntimeException{
// 提供有一个带参数的构造方法,并在方法体中使用super(msg)调用父类的构造方法进行初始化
public BombException(String msg){
super(msg);
}
}
class Food{
// 使用throws抛出一个异常序列,异常交给调用处处理
public static void eat(int num) throws BombException {
if (num > 10){
// 抛出一个异常对象
throw new BombException("吃太多了,肚子爆了");
}else {
System.out.println("正常开始吃,不怕吃胖");
}
}
}
public class Demo6 {
public static void main(String[] args){
try{
Food.eat(11);
}catch (BombException e){
// 处理BombException异常
e.printStackTrace();
}catch (Exception e){
// 处理其他异常
e.printStackTrace();
}
}
}
ArrayList数据的添加和输出(迭代器)
// 导入相关的依赖
import java.util.*;
public class Demo102 {
public static void main(String[] args) {
// 使用泛型ArrayList集合
ArrayList<String> list = new ArrayList<>();
// 向集合中添加元素
list.add("北京");
list.add("上海");
list.add("广州");
list.add("深圳");
list.add("成都");
list.add("杭州");
// 使用foreach输出
for (String e : list
) {
System.out.println(e);
}
System.out.println("------------------------------------------------");
// 指定位置添加元素
list.add(1,"日本");
// 使用迭代器输出
// 获取ArrayList的迭代器
Iterator<String> iterator = list.iterator();
// 使用迭代器遍历循环(当有下一个元素的时候,打印下一个元素)
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("元素个数"+list.size());
System.out.println("日本是否存在:"+list.contains("日本"));
list.remove("日本");
}
}
文件的输入和输出
字节输入流
import java.io.*;
import java.util.Scanner;
public class Demo103 {
public static void main(String[] args) {
// 建立一个从键盘接收数据的扫描器
Scanner scanner = new Scanner(System.in);
// 声明文件字节输入流
FileOutputStream fileOutputStream = null;
try {
// 实例化文件字节输入流
fileOutputStream = new FileOutputStream("test.txt");
System.out.println("请输入内容");
String str = scanner.nextLine();
// 将数据写入文件
fileOutputStream.write(str.getBytes());
System.out.println("已保存");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭文件输入流
fileOutputStream.close();
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("------------------------");
System.out.println("读取数据");
// 声明字节输入流
FileInputStream fileInputStream = null;
try {
// 实例化文件字节输入流
fileInputStream = new FileInputStream("test.txt");
// 创建一个长度为1024字节的数组作为缓冲区
byte[] bytes = new byte[1024];
// 用于保存实际读取的
int hasRead = 0;
// 使用循环重复读取文件中的数据
while ((hasRead = fileInputStream.read(bytes)) > 0) {
// 将缓冲区的数据转换成字符串输出
System.out.println(new String(bytes, 0, hasRead));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭文件输入流
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
字符输入流
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Demo104 {
public static void main(String[] args) {
// 建立一个从键盘接收数据的扫描器
Scanner scanner = new Scanner(System.in);
// 声明文件字符输入流
FileWriter fileWriter = null;
try {
// 实例化文件字符输入流
fileWriter = new FileWriter("text.txt");
System.out.println("请输入内容");
String str = scanner.nextLine();
// 将数据写入文件
fileWriter.write(str);
System.out.println("已保存");
}catch (IOException e){
e.printStackTrace();
}finally {
try {
// 关闭文件字符输入流
fileWriter.close();
scanner.close();
}catch (IOException e){
e.printStackTrace();
}
}
System.out.println("读取数据");
// 声明一个BufferedReader(缓冲字符输入流)对象
BufferedReader bufferedReader = null;
try{
// 实例化BufferedReader(缓冲字符输入流),并连接FileReader流用于读文件
bufferedReader = new BufferedReader(new FileReader("text.txt"));
// 存储每行读入数据的结果
String result = null;
// 循环读文件,一次读一行
while ((result = bufferedReader.readLine())!=null){
System.out.println(result);
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
// 关闭缓冲流
bufferedReader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
对象流的输入和输出(对象序列化)
import java.io.*;
// 定义一个可以序列化的Student类
// 只有实现Serializable接口的对象才可以利用序列化工具保存和复原
class Student105 implements Serializable {
private String studentId;
private String name;
private int age;
// 构造函数
public Student105(String studentId, String name, int age) {
this.studentId = studentId;
this.name = name;
this.age = age;
}
// get和set方法
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// 重写toString方法
@Override
public String toString() {
return "姓名:" + this.name + ",学号:" + this.studentId + ",年龄:" + this.age;
}
}
public class Demo105 {
public static void main(String[] args) {
System.out.println("序列化");
// 创建一个对象输出流
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("object.txt"))) {
// 实例化一个student对象
Student105 student1 = new Student105("17031000", "张三", 20);
// 把对象写入到文件中
objectOutputStream.writeObject(student1);
//
objectOutputStream.flush();
System.out.println("序列化完毕");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("反序列化");
// 创建一个对象输入流
try (ObjectInputStream objectIutputStream = new ObjectInputStream(new FileInputStream("object.txt"))) {
// 从ObjectInputStream对象输入流中读取一个对象,并强制转换为Student105对象
Student105 student = (Student105) objectIutputStream.readObject();
System.out.println("反序列化完毕,读出结果如下");
System.out.println(student);
} catch (Exception e) {
e.printStackTrace();
}
}
}
树结构(计算机系组织结构图)
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
public class Demo106 extends JFrame {
private DefaultMutableTreeNode root;
private DefaultTreeModel model;
private JTree tree;
private JTextArea textArea;
private JPanel panel;
// 构造方法
public Demo106() {
super("计算机系组织结构图");
// 实例化树的根节点
root = makeSampleTree();
// 实例化树模型
model =new DefaultTreeModel(root);
// 实例化一棵树
tree = new JTree(model);
// 设置树的选择模式是单一节点选择模式
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
// 注册树的监听对象,监听选择不同的树节点
tree.addTreeSelectionListener(new TreeSelectionListener() {
// 重写树的选择事件处理方法
@Override
public void valueChanged(TreeSelectionEvent e) {
// 获取选中节点的路径
TreePath path = tree.getSelectionPath();
if (path==null){
return;
}
// 获取选中的节点对象
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
// 获取选中节点的内容,并显示到文本域
textArea.setText(selectedNode.getUserObject().toString());
}
});
// 实例化一个面板对象,布局1行2列
panel = new JPanel(new GridLayout(1,2));
// 在面板左侧放置树
panel.add(new JScrollPane(tree));
textArea = new JTextArea();
// 面板右侧放置文本域
panel.add(new JScrollPane(textArea));
// 将面板添加到窗体
this.add(panel);
// 设置窗口大小和位置
this.setSize(400,300);
this.setLocation(200,100);
// 设置窗口关闭方式为退出应用程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口可视
this.setVisible(true);
}
public DefaultMutableTreeNode makeSampleTree() {
// 实例化树节点,并添加节点到相应节点中
DefaultMutableTreeNode root = new DefaultMutableTreeNode("西安交通大学城市学院");
DefaultMutableTreeNode jisuanji = new DefaultMutableTreeNode("计算机系");
DefaultMutableTreeNode dianxin = new DefaultMutableTreeNode("电信系");
DefaultMutableTreeNode jixie = new DefaultMutableTreeNode("机械系");
DefaultMutableTreeNode tujian = new DefaultMutableTreeNode("土建系");
root.add(jisuanji);
root.add(dianxin);
root.add(jixie);
root.add(tujian);
DefaultMutableTreeNode jike = new DefaultMutableTreeNode("计算机科学与技术");
DefaultMutableTreeNode ruanjian = new DefaultMutableTreeNode("软件工程");
DefaultMutableTreeNode wulianwang = new DefaultMutableTreeNode("物联网工程");
DefaultMutableTreeNode wangluo = new DefaultMutableTreeNode("网络工程");
jisuanji.add(jike);
jisuanji.add(ruanjian);
jisuanji.add(wulianwang);
jisuanji.add(wangluo);
return root;
}
public static void main(String[] args) {
new Demo106();
}
}
银行账号(线程同步)
同步代码块
class BankAccount107 {
// 银行账号
private String bankNo;
// 银行余额
private double balance;
// 构造方法
public BankAccount107(String bankNo, double balance) {
this.bankNo = bankNo;
this.balance = balance;
}
//get和set方法
public String getBankNo() {
return bankNo;
}
public void setBankNo(String bankNo) {
this.bankNo = bankNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
// 多线程需继承Thread类
public class Demo107 extends Thread {
// 银行账户
private BankAccount107 account;
// 操作金额
private double money;
// 构造方法
public Demo107(String name, BankAccount107 account, double money) {
super(name);
this.account = account;
this.money = money;
}
// 重写run方法
@Override
public void run() {
synchronized (this.account) {
// 获取目前账户的金额
double d = this.account.getBalance();
// 如果操作金额小于0为取钱
// 如果操作金额大于0为存钱
// 账号余额必须大于取钱金额
if (money < 0 && d < -money) {
System.out.println(this.getName() + "操作失败,余额不足");
return;
} else {
d += money;
System.out.println("操作成功,余额为:" + d);
try {
//休眠1毫秒
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.account.setBalance(d);
}
}
}
public static void main(String[] args) {
// 创建一个银行账户
BankAccount107 account = new BankAccount107("6102021100", 5000);
Demo107 demo1 = new Demo107("T001", account, 1000);
Demo107 demo2 = new Demo107("T002", account, -2000);
Demo107 demo3 = new Demo107("T003", account, -3000);
Demo107 demo4 = new Demo107("T004", account, -2000);
Demo107 demo5 = new Demo107("T005", account, 1000);
Demo107 demo6 = new Demo107("T006", account, -1000);
Demo107 demo7 = new Demo107("T007", account, 3000);
Demo107 demo8 = new Demo107("T008", account, -5000);
// 启动线程
demo1.start();
demo2.start();
demo3.start();
demo4.start();
demo5.start();
demo6.start();
demo7.start();
demo8.start();
//等待子线程完成
try {
demo1.join();
demo2.join();
demo3.join();
demo4.join();
demo5.join();
demo6.join();
demo7.join();
demo8.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("账号:" + account.getBankNo() + ",余额:" + account.getBalance());
}
}
同步方法
class BankAccount108 {
// 银行账号
private String bankNo;
// 银行余额
private double balance;
// 构造方法
public BankAccount108(String bankNo, double balance) {
this.bankNo = bankNo;
this.balance = balance;
}
//get和set方法
public String getBankNo() {
return bankNo;
}
public void setBankNo(String bankNo) {
this.bankNo = bankNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public synchronized void access(double money) {
// 如果操作金额小于0为取钱
// 如果操作金额大于0为存钱
// 账号余额必须大于取钱金额
if (money < 0 && balance < -money) {
System.out.println(Thread.currentThread().getName() + "操作失败,余额不足");
return;
} else {
balance += money;
System.out.println("操作成功,余额为:" + balance);
try {
//休眠1毫秒
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 多线程需继承Thread类
public class Demo108 extends Thread {
// 银行账户
private BankAccount108 account;
// 操作金额
private double money;
// 构造方法
public Demo108(String name, BankAccount108 account, double money) {
super(name);
this.account = account;
this.money = money;
}
// 线程任务
@Override
public void run() {
// 调用同步方法
this.account.access(money);
}
public static void main(String[] args) {
// 创建一个银行账户
BankAccount108 account = new BankAccount108("6102021100", 5000);
Demo108 demo1 = new Demo108("T001", account, 1000);
Demo108 demo2 = new Demo108("T002", account, -2000);
Demo108 demo3 = new Demo108("T003", account, -3000);
Demo108 demo4 = new Demo108("T004", account, -2000);
Demo108 demo5 = new Demo108("T005", account, 1000);
Demo108 demo6 = new Demo108("T006", account, -1000);
Demo108 demo7 = new Demo108("T007", account, 3000);
Demo108 demo8 = new Demo108("T008", account, -5000);
// 启动线程
demo1.start();
demo2.start();
demo3.start();
demo4.start();
demo5.start();
demo6.start();
demo7.start();
demo8.start();
//等待子线程完成
try {
demo1.join();
demo2.join();
demo3.join();
demo4.join();
demo5.join();
demo6.join();
demo7.join();
demo8.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("账号:" + account.getBankNo() + ",余额:" + account.getBalance());
}
}
同步锁
import java.util.concurrent.locks.ReentrantLock;
class BankAccount109 {
// 银行账号
private String bankNo;
// 银行余额
private double balance;
// 定义锁对象
private final ReentrantLock lock = new ReentrantLock();
// 构造方法
public BankAccount109(String bankNo, double balance) {
this.bankNo = bankNo;
this.balance = balance;
}
//get和set方法
public String getBankNo() {
return bankNo;
}
public void setBankNo(String bankNo) {
this.bankNo = bankNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void access(double money) {
// 加锁
lock.lock();
try {
// 如果操作金额小于0为取钱
// 如果操作金额大于0为存钱
// 账号余额必须大于取钱金额
if (money < 0 && balance < -money) {
System.out.println(Thread.currentThread().getName() + "操作失败,余额不足");
return;
} else {
balance += money;
System.out.println("操作成功,余额为:" + balance);
try {
//休眠1毫秒
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
// 释放锁
lock.unlock();
}
}
}
// 多线程需继承Thread类
public class Demo109 extends Thread {
// 银行账户
private BankAccount109 account;
// 操作金额
private double money;
// 构造方法
public Demo109(String name, BankAccount109 account, double money) {
super(name);
this.account = account;
this.money = money;
}
// 线程任务
@Override
public void run() {
// 调用同步锁方法
this.account.access(money);
}
public static void main(String[] args) {
// 创建一个银行账户
BankAccount109 account = new BankAccount109("6102021100", 5000);
Demo109 demo1 = new Demo109("T001", account, 1000);
Demo109 demo2 = new Demo109("T002", account, -2000);
Demo109 demo3 = new Demo109("T003", account, -3000);
Demo109 demo4 = new Demo109("T004", account, -2000);
Demo109 demo5 = new Demo109("T005", account, 1000);
Demo109 demo6 = new Demo109("T006", account, -1000);
Demo109 demo7 = new Demo109("T007", account, 3000);
Demo109 demo8 = new Demo109("T008", account, -5000);
// 启动线程
demo1.start();
demo2.start();
demo3.start();
demo4.start();
demo5.start();
demo6.start();
demo7.start();
demo8.start();
//等待子线程完成
try {
demo1.join();
demo2.join();
demo3.join();
demo4.join();
demo5.join();
demo6.join();
demo7.join();
demo8.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("账号:" + account.getBankNo() + ",余额:" + account.getBalance());
}
}
登录界面+事件处理
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Demo110 extends JFrame {
// 声明组件
private JPanel panel;
private JLabel labelname, labelpassword, labelmsg;
// 声明一个文本框
private JTextField textFieldname;
private JPasswordField passwordField;
// 声明两个按钮
private JButton buttonSumbit, buttonReset;
// 构造方法
public Demo110() {
super("登录界面");
// 创建面板,面板布局为null
panel = new JPanel(null);
// 实例化标签
labelname = new JLabel("用户名");
labelpassword = new JLabel("密码");
// 实例化要显示的信息
labelmsg = new JLabel();
// 设置信息颜色
labelmsg.setForeground(Color.red);
// 创建一个文本框
textFieldname = new JTextField(20);
// 创建一个密码框
passwordField = new JPasswordField(20);
// 设置密码框显示字符
passwordField.setEchoChar('*');
// 创建两个按钮
buttonSumbit = new JButton("登录");
buttonReset = new JButton("取消");
// 注册确定按钮的事件处理
buttonSumbit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 设置信息标签为空
labelmsg.setText("");
// 获取用户输入的用户名
String stringName = textFieldname.getText();
System.out.println("用户名:" + stringName);
if (stringName == null || stringName.equals("")) {
labelmsg.setText("用户名不能为空");
return;
}
// 获取用户输入的密码
String stringPassword = passwordField.getText();
System.out.println("密码:" + stringPassword);
if (stringPassword == null || stringPassword.equals("")) {
labelmsg.setText("密码不能为空");
return;
}
labelmsg.setText("登录成功");
}
});
// 注册重置按钮的事件处理
buttonReset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 清空所有文本
textFieldname.setText("");
passwordField.setText("");
// 设置标签为空
labelmsg.setText("");
}
});
// 定位所有组件
labelname.setBounds(30, 30, 60, 25);
labelpassword.setBounds(30, 100, 60, 25);
textFieldname.setBounds(95, 30, 125, 25);
passwordField.setBounds(95, 100, 125, 25);
buttonSumbit.setBounds(50, 150, 75, 30);
buttonReset.setBounds(150, 150, 75, 30);
labelmsg.setBounds(50, 200, 100, 25);
// 将组件添加到面板中
panel.add(labelname);
panel.add(labelpassword);
panel.add(textFieldname);
panel.add(passwordField);
panel.add(buttonSumbit);
panel.add(buttonReset);
panel.add(labelmsg);
// 将面板添加到窗体中
this.add(panel);
// 设置窗体的位置和大小
this.setBounds(200, 100, 280, 300);
// 设置默认退出方式
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口可视
this.setVisible(true);
}
public static void main(String[] args) {
new Demo110();
}
}
系及专业选择,加事件处理(组合框)
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.StringStack;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Stack;
public class Demo111 extends JFrame {
// 声明组件
private JPanel panel;
private JLabel labelDepartment, labelMajor;
private JComboBox comboBoxDepartment, comboBoxMajor;
// 构造方法
public Demo111() {
super("系别专业选择");
panel = new JPanel();
labelDepartment = new JLabel("系别");
labelMajor = new JLabel("专业");
// 创建组合框,并且使用字符串数组初始化其选项列表
comboBoxDepartment = new JComboBox(new String[]{"计算机系", "经济系", "管理系"});
comboBoxMajor = new JComboBox();
comboBoxDepartment.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int i = 0;
// 获取用户选中的选项下标
i = comboBoxDepartment.getSelectedIndex();
// 清空组合框的选项
comboBoxMajor.removeAllItems();
// 根据用户选择不同的系别添加不同的专业
switch (i) {
case 0: {
comboBoxMajor.addItem("计算机科学与技术");
comboBoxMajor.addItem("网络工程");
comboBoxMajor.addItem("软件工程");
comboBoxMajor.addItem("物联网工程");
break;
}
case 1: {
comboBoxMajor.addItem("经济学");
comboBoxMajor.addItem("国际贸易");
break;
}
case 2: {
comboBoxMajor.addItem("会计学");
comboBoxMajor.addItem("工商管理");
break;
}
}
}
});
panel.add(labelDepartment);
panel.add(comboBoxDepartment);
panel.add(labelMajor);
panel.add(comboBoxMajor);
// 将面板添加到窗体
this.add(panel);
this.setBounds(200, 200, 500, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new Demo111();
}
}
本文地址:https://blog.csdn.net/qq_29537269/article/details/107059133