作业一

  1. 计算多项式1!+2!+3!…+n!,当多项式之和超过10000时停止,并输出累加之和以及n的值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class factorial {  
  
    public static void main(String[] args) {  
        int sum = 0;  
        int n = 1;  
        int next = 0;  
        while (next <= 10000) {  
            sum = sum + fun(n);  
            next = sum + fun(++n);  
        }  
        System.out.printf("累加之和为 %d, 数字 n 为 %d\n", sum, n-1);  
    }  
  
    public static int fun(int n) {  
        if (n == 1 || n == 0)  
            return 1;  
        return n * fun(n - 1);  
    }  
  
}  

2. 从标准输入端输入一个字符,判断字符是数字、还是西文字母还是其他的字符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Scanner;  
  
public class judge {  
    public static void main(String[] args) {  
        while (true) {  
            Scanner scanner = new Scanner(System.in);  
            System.out.println("请输入一个字符以进行判断,输入Q结束程序:");  
            char c = scanner.next().charAt(0);  
            if (c == 'q' || c == 'Q')  
                break;  
            if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')  
                System.out.println(c + "是一个西文字母");  
            else if (c >= '0' && c <= '9')  
                System.out.println(c + "是一个数字");  
            else  
                System.out.println(c + "是其他字符");  
        }  
    }  
}  
  1. 利用辗转相除法(欧几里得算法)求两个正整数的最大公约数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Scanner;  
  
public class Euclidean {  
    public static int Greatest_common_divisor(int num1, int num2) {  
        if (num1 < 0 || num2 < 0) {  
            return -1;  
        }  
        if (num2 == 0) {  
            return num1;  
        }  
        while (num1 % num2 != 0) {  
            int numtemp = num1 % num2;  
            num1 = num2;  
            num2 = numtemp;  
        }  
        return num2;  
    }  
    public static void main(String[] args)  
    {  
        int a,b;  
        Scanner scanner = new Scanner(System.in);  
        System.out.print("输入第一个数字: ");  
        a = scanner.nextInt();  
        System.out.print("输入第二个数字: ");  
        b = scanner.nextInt();  
        int ans= Greatest_common_divisor(a,b);  
        System.out.println("最大公约数为 "+ ans);  
    }  
}  

  1. 假设一个数在1000到1100之间,那除以3结果余2,;除以5结果余3,;除以7结果余2(中国剩余定理),求此数。
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.Scanner;  
  
public class Chinese_remainder_theorem {  
    public static void main(String[] args) {  
  
        for (int i = 1000; i <= 1100; i++)  
            if (i % 3 == 2 && i % 5 == 3 && i % 7 == 2)  
                System.out.println(i);  
  
    }  
  
}  

  1. 小球从100米高度自由落下,每次触地后反弹到原来高度的一半,求第10次触地时经历的总路程以及第10次反弹高度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.Scanner;  
  
public class ball {  
    public static void main(String[] args) {  
        Scanner scanner =new Scanner(System.in);  
        System.out.print("输入高度: ");  
        double height = scanner.nextInt();  
        System.out.print("输入次数: ");  
        int n = scanner.nextInt();  
        double sum = 0;  
        for(int i = 1;i<=n;i++){  
            sum = height+height/2+sum;//一次落地距离+弹起距离+已经过路程  
            height/=2;  
            System.out.printf("第 %d 次弹跳高度为: %f米\n",i,height);  
        }  
        System.out.println("**************************");  
        sum-=height;  
        System.out.println("共经过"+sum+"米");  
        System.out.println("第10次弹起的高度为:"+height+"米");  
    }  
}  

作业二

读程序,写结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class A {
public String Show(D obj) { return ("A and D"); }
public String Show(A obj) { return ("A and A"); }
}
class B extends A {
public String Show(B obj) { return ("B and B"); }
public String Show(A obj) { return ("B and A"); }
}
class C extends B {
public String Show(C obj) { return ("C and C"); }
public String Show(B obj) { return ("C and B"); }
}
class D extends B {
public String Show(D obj) { return ("D and D"); }
public String Show(B obj) { return ("D and B"); }
}

public class mainTest {
public static void main(String args[]){
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println(a1.Show(b));
System.out.println(a1.Show(c));
System.out.println(a1.Show(d));
System.out.println(a2.Show(b));
System.out.println(a2.Show(c));
System.out.println(a2.Show(d));
System.out.println(b.Show(b));
System.out.println(b.Show(c));
System.out.println(b.Show(d));
}}

分析:

第一个输出:B自动转换为父类A,因此输出A and A;

第二个输出:与上面同理,自动转换为父类A,因此输出A and A;

第三个输出:调用A类的第一个Show函数,输出A and A;

第四个输出:首先因为引用类型为A类,所以系统想要执行A类的方法,但A类并没有找到类型匹配的方法,于是将参数b自动转化为父类,执行Show(A obj)方法,又因为a1实际指向了B类的对象,子类B重写了这个方法,因此优先执行子类的方法,于是输出B and A;

第五个输出:与上面同理,只是又将参数c多转化了一步,输出B and A;

第六个输出:与第四个类似,由于a2的引用类型是A类,而class A包含Show(D obj)方法,因此直接输出A and D;

第七个输出:直接调用B的Show(B obj)方法,因此输出B and B;

第八个输出:因为没有匹配的方法,因此参数c自动转换为父类B,因此调用Show(B obj)方法,输出B and B;

第九个输出:因为B的父类A类中方法Show(D obj)匹配,因此调用此方法输出A and D。

答案:

1
2
3
4
5
6
7
8
9
A and A  
A and A  
A and D  
B and A  
B and A  
A and D  
B and B  
B and B  
A and D  

读程序,写结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Base { 
private String name = "base";
public Base() {
tellName();}

public void tellName() {
System.out.println("Base tell name: " + name); }
}
public class Dervied extends Base {
private String name = "dervied";
public Dervied() {
tellName();}

public void tellName() {
System.out.println("Dervied tell name: " + name);}

public static void main(String[] args){

new Dervied();
}}

分析:

当主函数语句new Dervied();执行时,首先初始化Dervied类,但又因为Dervied类继承了Base类,因此先初始化Base类。Base类的private变量name被赋初值“base”,然后进入构造函数执行tellName(),但因为子类Base重写了该方法,因此实际上进入子类的tellName()函数执行,但是此时子类的name仍未初始化,因此为null,输出“Dervied tell name: null”。然后开始子类初始化,Dervied类的private变量name被赋初值“dervied”,然后执行构造函数tellName(),输出“Dervied tell name: dervied”。

答案:

1
2
Dervied tell name: null  
Dervied tell name: dervied

练习3:Example2:生成动物

首先来看Animal类,这是一个抽象类,其方法在后面的子类进行实现。包括getAnimalCount()用来获取每一类动物的数量;Increaseanimals()用于增加每类动物的个数;静态变量sumall用于统计所有动物的总数。

1
2
3
4
5
6
package com.company;
public abstract class Animal {
public abstract void getAnimalCount();
public abstract void Increaseanimals();
public static int sumall = 0;
}

然后是AnimalFactory类,用于生成动物。首先构造动物的静态对象,然后在getAnimal()函数中分别调用动物子类的两个函数即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.company;

public class AnimalFactory {
static Tiger tiger = new Tiger();
static Rabbit rabbit = new Rabbit();
static Bear bear = new Bear();
static Panda panda = new Panda();

public static Animal getAnimal(String type){
Animal.sumall++;
if("tiger".equalsIgnoreCase(type)) {
tiger.Increaseanimals();
tiger.getAnimalCount();
}
else if("rabbit".equalsIgnoreCase(type)){
rabbit.Increaseanimals();
rabbit.getAnimalCount();
}
else if ("bear".equalsIgnoreCase(type)){
bear.Increaseanimals();
bear.getAnimalCount();
}
else if ("panda".equalsIgnoreCase(type)){
panda.Increaseanimals();
panda.getAnimalCount();
}
else {
Animal.sumall--;
System.out.println("ERROR! NO SUCH ANIMAL! ");
}
return null;
}
}

然后是动物类,分别继承了Animal类。因为每个动物类仅有类名不同,我们以Bear类和Rabbit类为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.company;

public class Bear extends Animal {
private int count = 0;
public Bear() {
}

@Override
public void Increaseanimals() {
this.count++;
}
@Override
public void getAnimalCount() {
System.out.println("The current total number of " + this.getClass().getName().substring(12) + "(s) is: " + this.count);
}

}

下面是Rabbit类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.company;

public class Rabbit extends Animal {
private int count = 0;
public Rabbit(){
}

@Override
public void Increaseanimals(){
this.count++;
}

@Override
public void getAnimalCount() {
System.out.println("The current total number of "+this.getClass().getName().substring(12)+"(s) is: " + this.count);
}

}

可以看到两个动物类仅有类名不同,其他代码均可复用,包括输出语句,这也意味着加入新的动物极其简单,只需要复制一份文件然后修改类名即可,后面做一下演示。

最后看一下主类,主要是while循环、提示信息以及输入输出流:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.company;
import java.util.Scanner;
/**
* @Title:AnimalFactory
* @author ZHANG Xiyuan, CUMT
* @CreateDate: 2021.12.03
*/

public class Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("********* Welcome to the Animal Factory! *********");
System.out.println("There are the following animals to choose from: \nBear, Panda, Rabbit, Tiger");
System.out.println("If you want to add an animal, you only need to enter the name of the above animal, not case sensitive.");
System.out.println("Type q to exit.");
while (true) {
System.out.print("\nPlease input an animal: ");
String in = scanner.next();
if(in.equalsIgnoreCase("q"))
break;
AnimalFactory.getAnimal(in);
System.out.println("The current total number of all animals is: " + Animal.sumall);
}
}

}

下面是UML类图:

效果演示:

最后演示一下如何扩展AnimalFactory,添加一种动物,假如添加Elephant大象,非常简单:

1.在项目内复制随意一个动物类文件,改名,动物类内其他代码不用改动;

2. 在AnimalFactory内添加一个静态对象

1
static Elephant elephant = new Elephant();

3. 加一个 else if语句,同样复制一下改名即可:

完成。演示一下效果:

作业三

用泛型List管理学生信息

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
public class Student {
private String stuid;
private String name;
private int age;
private String address;

public Student(String stuid, String name, int age, String address) {
this.stuid = stuid;
this.name = name;
this.age = age;
this.address = address;
}

public String getStuID() {
return stuid;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public String getAddress() {
return address;
}

}






import java.util.ArrayList;
import java.util.Scanner;

public class StudentManager {
public static void main(String[] args) {
System.out.println("---------------- Welcome to the Student Management System ----------------");

ArrayList<Student> stuCollection = new ArrayList<Student>();
Student stu1 = new Student("08190001","Alex",20,"Chaoyang District, Beijing");
Student stu2 = new Student("08190018","Christian",21,"Quanshan District, Xuzhou City");
Student stu3 = new Student("08198888","Edward",19,"Brooklyn, New York City");
Student stu4 = new Student("08199900","Herman",20,"East Bay, San Francisco");

stuCollection.add(stu1);
stuCollection.add(stu2);
stuCollection.add(stu3);
stuCollection.add(stu4);

while (true) {

System.out.println("\n[A]AddStudent\t[D]DeleteStudent\t[E]EditStudent\n[V]ViewStudents\t[F]FindStudent\t\t[Q]Quit\n");

System.out.println("Please enter function code: ");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();

switch (line.toUpperCase()) {
case "A" -> addStudent(stuCollection);
case "D" -> deleteStudent(stuCollection);
case "E" -> modifyStudentInformation(stuCollection);
case "V" -> viewAllStudent(stuCollection);
case "F" -> findStudentAndDisplay(stuCollection);
case "Q" -> System.exit(0);
default -> System.out.println("⚠ Incorrect function code!\n");
}
}
}

public static void addStudent(ArrayList<Student> stuCollection) {
Scanner sc = new Scanner(System.in);
String stuid;

while (true) {
System.out.println("Enter student ID:");
stuid = sc.nextLine();

int i = findStudent(stuCollection, stuid);
if (i != -1) {
System.out.println("⚠ The student information you want to add already exists The student information you want to add already exists!");
} else {
break;
}
}

System.out.println("Enter the student's name:");
String name = sc.nextLine();

System.out.println("Enter the age of the student:");
int age = sc.nextInt();

System.out.println("Enter the student's residential address:");
String address = sc.next();

Student stu = new Student(stuid, name, age, address);
stuCollection.add(stu);
System.out.println("✅️Added successfully.");

}

public static int findStudent(ArrayList<Student> stuCollection, String stuid) {
for (int i = 0; i < stuCollection.size(); i++) {
Student stu = stuCollection.get(i);
if (stuid.equals(stu.getStuID())) {
return i;
}
}
return -1;
}

public static void findStudentAndDisplay(ArrayList<Student> stuCollection){
System.out.println("Please enter the student ID of the student you want to find:");
Scanner sc = new Scanner(System.in);
String stuid = sc.nextLine();
int i = findStudent(stuCollection,stuid);
if (i == -1) {
System.out.println("⚠ The student's information you want to find does not exist!");
return;
}
System.out.println("Find the following students:");
System.out.format("%-14s%-14s%-14s%-14s","StudentID","Name","Age","Address");
System.out.println();
System.out.format("%-14s%-14s%-14s%-14s\n", stuCollection.get(i).getStuID(),stuCollection.get(i).getName(),stuCollection.get(i).getAge(),stuCollection.get(i).getAddress());

}

public static void viewAllStudent(ArrayList<Student> stuCollection) {
if (stuCollection.size() == 0) {
System.out.println("⚠ No student found.");
return;
}
System.out.format("%-14s%-14s%-14s%-14s","StudentID","Name","Age","Address");
System.out.println();
for (Student student : stuCollection) {
System.out.format("%-14s%-14s%-14s%-14s\n",student.getStuID(),student.getName(),student.getAge(),student.getAddress());
}
}

public static void deleteStudent(ArrayList<Student> stuCollection) {
System.out.println("Please enter the student ID you want to delete:");
viewAllStudent(stuCollection);
Scanner sc = new Scanner(System.in);
String stuid = sc.nextLine();

int i = findStudent(stuCollection, stuid);
if (i == -1) {
System.out.println("⚠ The student's information you want to delete does not exist!");
return;
}
stuCollection.remove(i);
System.out.println("✅️Deleted successfully.");
}

public static void modifyStudentInformation(ArrayList<Student> stuCollection) {
System.out.println("Please enter the student ID of the student you want to modify:");
viewAllStudent(stuCollection);
Scanner sc = new Scanner(System.in);
String stuid = sc.nextLine();

int i = findStudent(stuCollection, stuid);
if (i == -1) {
System.out.println("⚠ The student's information you want to modify does not exist");
return;
}

System.out.println("Please enter the revised name:");
String name = sc.nextLine();

System.out.println("Please enter the revised age:");
int age = sc.nextInt();

System.out.println("Please enter the revised address:");
String address = sc.next();

Student s = new Student(stuid, name, age, address);
stuCollection.set(i, s);
System.out.println("✅️Modified successfully.");
}
}

运行结果:

1.首先查看学生(系统自带四个学生)。然后添加学生Max。

2. 再次查看学生,Max已被添加。

3.输入E(不区分大小写)修改学生。此时将会自动显示所有学生。如果输入错误的学号将会报错。

修改学号为08190001的学生(Alex)的信息。之后查看所有学生信息,Alex的信息已被修改。

4.删除学生。同样的,如果输入错误的学号将会报错。现在删除Edward的信息,删除完成后查看所有学生信息,Edward已被删除。

5. 查找学生。如果输入错误的功能代号(Function Code)将会报错。查找学号为08199900的学生,如果找到则返回信息。输入Q退出系统。

设计一个求一元二次方程根的程序

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import java.io.Serializable;

public class BinaryLinearEquation implements Serializable {
public static String show;
private final double a;
private final double b;
private final double c;
private double x1;
private double x2;
private double real;
private double complex;
private boolean isComplex = false;


public BinaryLinearEquation(double A, double B, double C) {
this.a = A;
this.b = B;
this.c = C;
}

public String getInfo() {
if(!this.isComplex)
return "The equation is\n" + this.a + "x^2 + " + this.b + "x + " + this.c +
"\nThe solution of this equation is:\n" +
"x1 = " + this.x1 + "\n" +
"x2 = " + this.x2;
else
return "The equation is\n" + this.a + "x^2 + " + this.b + "x + " + this.c +
"\nThe solution of this equation is:\n" +
"x1 = " + this.real + " + " + this.complex + "i\n"+
"x2 = " + this.real + " - " + this.complex + "i";
}

public void Solve() throws NonQuadraticEquationException {
double delta = this.b * this.b - 4 * this.a * this.c;
if (this.a == 0)
{
throw new NonQuadraticEquationException();
}
if (delta < 0) {
this.isComplex = true;
if (b != 0) {
this.real = ((-1) * b) / (2 * a);
this.complex = Math.sqrt(-1 * delta) / (2 * a);
show = "The equation has a pair of conjugate complex roots.\n" +
"x1 = " + this.real + " + " + this.complex + "i\n" +
"x2 = " + this.real + " - " + this.complex + "i";
} else {
this.real = 0;
this.complex = Math.sqrt(-1 * delta) / (2 * a);
show = "The equation has a pair of opposite virtual roots.\n" +
"x1 = 0 - " + this.complex + "i\n" +
"x2 = 0 + " + this.complex + "i";
}
} else {
this.x1 = ((-this.b) + Math.sqrt(delta)) / 2 * this.a;
if (delta == 0) {
this.x2 = this.x1;
}
this.x2 = ((-this.b) - Math.sqrt(delta)) / 2 * this.a;
show = "x1 = " + this.x1 + "\nx2 = " + this.x2;
}
}

}


public class NonQuadraticEquationException extends Exception {
public String message;
public NonQuadraticEquationException() {
message = "The input equation is not a binary linear equation!";
}
public String toString() {
return message;
}
}


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

class CalcPanel extends Panel {
JLabel label1, label2, label3;
JTextField text1, text2, text3;
JButton button1,button2,button3,button4;

CalcPanel() {
this.setLayout(new GridLayout(0,1,10,10));
text1 = new JTextField();
text1.setPreferredSize(text1.getSize());
text2 = new JTextField();
text2.setPreferredSize(text1.getSize());
text3 = new JTextField();
text3.setPreferredSize(text1.getSize());
Font font = new Font(Font.SERIF, Font.PLAIN, 20);
label1 = new JLabel("Quadratic Term Coefficient");
label2 = new JLabel("Primary Term Coefficient");
label3 = new JLabel("Constant Term");
label1.setFont(font);
label1.setHorizontalAlignment(SwingConstants.HORIZONTAL);
label2.setFont(font);
label2.setHorizontalAlignment(SwingConstants.HORIZONTAL);
label3.setFont(font);
label3.setHorizontalAlignment(SwingConstants.HORIZONTAL);
button1 = new JButton("Solve");
button2 = new JButton("Clear the input box");
button3 = new JButton("Exit");
button4 = new JButton("Deserialize");
button2.setSize(300,25);
button2.addActionListener(this::actionPerformedClear);
button3.addActionListener(this::actionPerformedExit);
button4.addActionListener(this::actionPerformedDeserialize);

add(label1);
add(text1);
add(label2);
add(text2);
add(label3);
add(text3);
add(button1);
add(button2);
add(button3);
add(button4);
}
//Clear
public void actionPerformedClear(ActionEvent e){
this.text1.setText("");
this.text2.setText("");
this.text3.setText("");
}
//Exit
public void actionPerformedExit(ActionEvent e){
int result = JOptionPane.showConfirmDialog(null, "Confirm to exit the interface?", "Exit",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.exit(0);
}
}
//Deserialize
public void actionPerformedDeserialize(ActionEvent e){
try(FileInputStream fis = new FileInputStream("file1.data");
ObjectInputStream ois = new ObjectInputStream(fis)) {
BinaryLinearEquation ex = (BinaryLinearEquation) ois.readObject();
JOptionPane.showMessageDialog(null,ex.getInfo(),"Deserialized Object",JOptionPane.INFORMATION_MESSAGE);
}catch (ClassNotFoundException | IOException exception){
JOptionPane.showMessageDialog(null,exception.getMessage(),"IOException",JOptionPane.WARNING_MESSAGE);
}
}
}

public class MainPanel extends JFrame implements ActionListener {
CalcPanel panel;
JTextArea textArea;
BinaryLinearEquation BLEquation;
public MainPanel() {
this.setLayout(new BorderLayout());
panel = new CalcPanel();
panel.button1.addActionListener(this);
textArea = new JTextArea();
textArea.setBounds(getX(), getY(), 100, 100);
Font font2 = new Font("苹方",Font.PLAIN,20);
textArea.setFont(font2);
add(panel, BorderLayout.NORTH);
add(textArea, BorderLayout.CENTER);
setBounds(450, 300, 600, 600);
setVisible(true);
setTitle("Binary Linear Equation Calculator");
validate();

}
//Solve
public void actionPerformed(ActionEvent e) {
try(FileOutputStream fos = new FileOutputStream("file1.data");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
BLEquation = new BinaryLinearEquation(Double.parseDouble(panel.text1.getText()), Double.parseDouble(panel.text2.getText()), Double.parseDouble(panel.text3.getText()));
BLEquation.Solve();
oos.writeObject(BLEquation);
}catch (IOException ioException) {
ioException.printStackTrace();
JOptionPane.showMessageDialog(null,ioException.getMessage(),"IOException",JOptionPane.WARNING_MESSAGE);
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(null,e1.getMessage(),"Input error!",JOptionPane.ERROR_MESSAGE);
this.textArea.setText(BinaryLinearEquation.show);
} catch (NonQuadraticEquationException e2) {
JOptionPane.showMessageDialog(null,e2.toString(),"Error in the form of the quadratic equation",JOptionPane.ERROR_MESSAGE);
}
this.textArea.setText(BinaryLinearEquation.show);
}
}

public class GUI {
public static void main(String[] args) {
new MainPanel();
}
}

运行结果(图形化界面):

  1. 界面如下所示。

2. 当输入为空时报错。

3. 求解
$$
{x^2} + x + 1 = 0
$$
提示该方程有一对共轭复根。

4.求解
$$
{x^2} + 1 = 0
$$
程序提示该方程有一对相反的虚根。

5. (1)下面演示一下序列化与反序列化功能。首先求解一个方程,例如
$$
{x^2} + 192x + 123 = 0
$$
求解如下。

(2)此时生成了file1.data文件,作为序列化后的对象(二进制文件)。我们用十六进制编辑器打开后,如下所示。

(3)然后点击Deserialize按钮,进行反序列化,程序将输出原方程和方程的解,如下所示。

(4)同样的,我们还可以序列化方程
$$
{x^2} + x + 1 = 0
$$
的对象,并进行反序列化,如下所示。

6. 下面我们来演示一下异常处理。开始时已经演示过空字符异常,这里不再重复。

(1)假如我们删除file1.data文件,系统将会捕捉到IOException,效果如下所示。

(2)如果在输入框内输入字母等非法字符,将会捕捉到NumberFormatException,效果如下。

(3)如果二次项系数输入为0,则会触发我们自定义的异常:

**NonQuadraticEquationException**,此时不是二元一次方程,程序报错。

7. 点击Clear the input box按钮将会清空输入框。

8. 点击Exit将会弹出确认对话框,确认后退出程序。

代码(命令行模式):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import javax.swing.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Scanner;

public class CommandLineMode {
public static void main(String[] args) {
double a=0, b=0, c=0;
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("\n******* Binary Linear Equation Calculator *******\n");
System.out.println("Please input the Quadratic Term Coefficient: ");
try {
a = scan.nextInt();
System.out.println("Please input the Primary Term Coefficient: ");
b = scan.nextInt();
System.out.println("Please input the Constant Term: ");
c = scan.nextInt();
} catch (Exception e) {
e.printStackTrace();
return;
}

BinaryLinearEquation BLEquation;

try (FileOutputStream fos = new FileOutputStream("file1.data");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
BLEquation = new BinaryLinearEquation(a, b, c);
BLEquation.Solve();
oos.writeObject(BLEquation);
} catch (IOException ioException) {
ioException.printStackTrace();
System.err.println(ioException.getMessage());
} catch (NumberFormatException e1) {
System.err.println(e1.getMessage());
System.out.println(BinaryLinearEquation.show);
} catch (NonQuadraticEquationException e2) {
System.err.println(e2.toString());
BinaryLinearEquation.show = "Refuse to calculate a linear equation.";
}
System.out.println(BinaryLinearEquation.show);
}
}
}

运行结果(命令行模式):

1. 求解
$$
{x^2} + 1 = 0
$$
程序提示该方程有一对相反的虚根。

2. 求解
$$
{x^2} + 192x + 123 = 0
$$

3. 求解
$$
{x^2} + x + 1 = 0
$$

  1. 当二次项系数为0时,程序报错:

同时,命令行模式也会将序列化后的对象存入file1.data文件。

作业四

正则表达式练习

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input mode:");
System.out.println("[P]Password\t\t\t\t[E]Email\n[I]Citizen ID number\t[Q]Quit");
String mode = scanner.next();
if (mode.equalsIgnoreCase("P")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please input your password:");
String pwd = sc.nextLine();
boolean isPwdSafe = validatePassword(pwd);
if (isPwdSafe)
System.out.println("Your password is acceptable.");
else
System.out.println("Your password does not meet the requirements.");
}
else if (mode.equalsIgnoreCase("E")){
Scanner sc = new Scanner(System.in);
System.out.println("Please input your email:");
String email = sc.nextLine();
boolean isEmail = validateEmail(email);
if (isEmail)
System.out.println("Your Email address is acceptable.");
else
System.out.println("Your Email address is not correct.");
}
else if (mode.equalsIgnoreCase("I")){
Scanner sc = new Scanner(System.in);
System.out.println("Please input your citizen ID number:");
String id = sc.nextLine();
boolean isIDNum = validateID(id);
if (isIDNum)
System.out.println("Your citizen ID number is acceptable.");
else
System.out.println("Your citizen ID number is not correct.");
}
else if (mode.equalsIgnoreCase("Q")){
break;
}
}
}


public static boolean validatePassword(String password) //密码输入校验方法
{
// 必须包含大小写字母和数字的组合,可以使用特殊字符,长度在6-16之间
boolean flag;
flag = password.matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,16}$");
return flag;
}
public static boolean validateEmail(String email)
{
boolean flag;
flag = email.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
return flag;
}
public static boolean validateID(String IDnum)
{
// 15位、18位
boolean flag;
flag = IDnum.matches("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)");
return flag;
}

}

运行结果:

1.满足密码复杂性需求,要求至少包含大小写字母和数字,可以使用特殊字符,长度在6-16位之间。

2.满足身份证号码规范,包括15位和18位。包括各部分规范检查,如月份不得大于12,每月不得多于31天,年份不得以17XX开头等。下图是18位身份证号码验证:

下图是15位身份证号码验证:

  1. 满足电子邮件规范:

利用鼠标事件启动3个线程分别在三个窗口中同时绘制动态图形

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Main{
public static void main(String[] args) {
new Control();
}
}

class Control extends JFrame{
JLabel label1;
Control(){
this.setBounds(200,450,400,200);
this.setTitle("控制中心");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font font = new Font("微软雅黑", Font.PLAIN, 23);
label1 = new JLabel("点击本窗口以同时启动三个线程");
label1.setFont(font);
add(label1);
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
actionPerformed();
}
});
this.setVisible(true);
}

public void actionPerformed(){
myThread ta = new myThread(200,100,0);
myThread tb = new myThread(500,100,1);
myThread tc = new myThread(800,100,2);
ta.setVisible(true);
tb.setVisible(true);
tc.setVisible(true);
}

}

class myThread extends JFrame implements Runnable {
int i = 0;
int tid;
Thread t;

myThread(int i, int j, int shape) {
this.tid = shape;
this.setBounds(i, j, 300, 300);
this.setTitle("Thread "+ shape);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
startThreadA();
}

void startThreadA() {
t = new Thread(this);
try {
t.start();
}catch (Exception e){
System.err.println(e.toString());
}
System.out.println("Thread "+this.tid +" has started successfully.");
}

public void run() {
for (i = 1; i <= 10; i++)
try {
repaint();
Thread.sleep(255);
} catch (Exception e) {
System.err.println(e.toString());
}
}
public void paint(Graphics g){
super.paint(g);
switch (this.tid){
case 0:
g.setColor(Color.RED);
if(i!=0)
g.fillRect(50+i*10,50+i*10,100,100);
break;
case 1:
g.setColor(Color.ORANGE);
if(i!=0)
g.fillOval(50+i*10,50+i*10,100,100);
break;
case 2:
g.setColor(new Color(7,244,161));
if(i!=0)
g.fillRoundRect(50+i*10,50+i*10,100,100,50,50);
break;
}

}
}

运行结果:

1.点击主控窗口同时启动三个线程,打开活动监视器,显示已创建3个线程:

2. 如下图所示,三个线程同时启动,各窗口同时绘制动态图形:

3. 再次点击主控窗口还可以创建更多的线程:

4.线程创建成功后在控制台输出日志信息: