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 {
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();
}
}
}
自定义异常
class BombException extends RuntimeException{
public BombException(String msg){
super(msg);
}
}
class Food{
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){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
}
ArrayList数据的添加和输出(迭代器)
import java.util.*;
public class Demo102 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("北京");
list.add("上海");
list.add("广州");
list.add("深圳");
list.add("成都");
list.add("杭州");
for (String e : list
) {
System.out.println(e);
}
System.out.println("------------------------------------------------");
list.add(1,"日本");
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");
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 = null;
try{
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.*;
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;
}
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;
}
@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"))) {
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"))) {
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());
}
});
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;
}
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 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;
}
@Override
public void run() {
synchronized (this.account) {
double d = this.account.getBalance();
if (money < 0 && d < -money) {
System.out.println(this.getName() + "操作失败,余额不足");
return;
} else {
d += money;
System.out.println("操作成功,余额为:" + d);
try {
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;
}
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) {
if (money < 0 && balance < -money) {
System.out.println(Thread.currentThread().getName() + "操作失败,余额不足");
return;
} else {
balance += money;
System.out.println("操作成功,余额为:" + balance);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
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;
}
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 {
if (money < 0 && balance < -money) {
System.out.println(Thread.currentThread().getName() + "操作失败,余额不足");
return;
} else {
balance += money;
System.out.println("操作成功,余额为:" + balance);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
}
}
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("登录界面");
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();
}
}