Java程序设计期末复习所有试题汇总(头歌)
第3关:方法的重写与重载
package case4;
public class overridingTest {
public static void main(String[] args) {
/********* begin *********/
// 声明并实例化一Person对象p
Person p = new Person();
p.setName("张三");
p.setAge(18);
p.talk();
}
}
class Person {
/********* begin *********/
private String name;
private int age;
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;
}
void talk(){
System.out.print("我是:"+ name + ",今年:" + age + "岁,我在哈佛大学上学");
}
}
class Student extends Person {
/********* begin *********/
/********* end *********/
}
第4关:抽象类
package case5;
public class abstractTest {
public static void main(String[] args) {
/********* begin *********/
// 分别实例化Student类与Worker类的对象,并调用各自构造方法初始化类属性。
new Student("张三", 20, "学生").talk();
new Worker("李四", 30, "工人").talk();
// 分别调用各自类中被复写的talk()方法 打印信息。
/********* end *********/
}
}
abstract class Person {
/********* begin *********/
String name;
int age;
String occupation;
public Person(String name, int age, String occupation) {
super();
this.name = name;
this.age = age;
this.occupation = occupation;
}
public abstract void talk();
/********* end *********/
}
//Student类继承自Person类,添加带三个参数的构造方法,复写talk()方法 返回姓名、年龄和职业信息
class Student extends Person {
public Student(String name, int age, String occupation) {
super(name, age, occupation);
// TODO 自动生成的构造函数存根
}
@Override
public void talk() {
// TODO 自动生成的方法存根
System.out.println("学生——>姓名:" + name + ",年龄:" + age + ",职业:" + occupation+"!");
}
/********* begin *********/
/********* end *********/
}
//Worker类继承自Person类,添加带三个参数的构造方法,复写talk()方法 返回姓名、年龄和职业信息
class Worker extends Person {
public Worker(String name, int age, String occupation) {
super(name, age, occupation);
// TODO 自动生成的构造函数存根
}
@Override
public void talk() {
// TODO 自动生成的方法存根
System.out.println("工人——>姓名:" + name + ",年龄:" + age + ",职业:" + occupation+"!");
}
/********* begin *********/
/********* end *********/
}
第5关:接口
package case7;
public class interfaceTest {
public static void main(String[] args) {
// 实例化一Student的对象s,并调用talk()方法,打印信息
/********* begin *********/
new Student().talk();
/********* end *********/
}
}
interface Person {
public static final String name = "张三";
public static final int age = 18;
public static final String occupation = "学生";
public abstract void talk();
/********* end *********/
}
//Student类继承自Person类,添加带三个参数的构造方法,复写talk()方法 返回姓名、年龄和职业信息
class Student implements Person {
@Override
public void talk() {
// TODO 自动生成的方法存根
System.out.println("学生——>姓名:" + name + ",年龄:" + age + ",职业:" + occupation+"!");
}
/********* begin *********/
/********* end *********/
}
第6关:什么是多态,怎么使用多态
package case8;
public class TestPolymorphism {
public static void main(String[] args) {
// 以多态方式分别实例化子类对象并调用eat()方法
/********* begin *********/
new Dog().eat();
new Cat().eat();
new Lion().eat();
/********* end *********/
}
}
class Animal {
/********* begin *********/
public void eat() {
System.out.println("eating");
}
/********* end *********/
}
//Dog类继承Animal类 复写eat()方法
class Dog extends Animal {
/********* begin *********/
public void eat() {
System.out.println("eating bread...");
}
/********* end *********/
}
//Cat类继承Animal类 复写eat()方法
class Cat extends Animal {
/********* begin *********/
public void eat() {
System.out.println("eating rat...");
}
/********* end *********/
}
//Lion类继承Animal类 复写eat()方法
class Lion extends Animal {
/********* begin *********/
public void eat() {
System.out.println("eating meat...");
}
/********* end *********/
}
Java高级特性 - 多线程练习题 第1关:顺序输出
package step1;
public class Task {
public static void main(String[] args) throws Exception {
/********* Begin *********/
//在这里创建线程, 开启线程
Object a = new Object();
Object b = new Object();
Object c = new Object();
MyThread ta = new MyThread("AA",b,a);
MyThread tb = new MyThread("BB",c,b);
MyThread tc = new MyThread("CC",a,c);
ta.start();
tb.start();
tc.start();
/********* End *********/
}
}
class MyThread extends Thread {
/********* Begin *********/
String threadName;
Object p;
Object s;
public MyThread(String threadName, Object p, Object s){
this.threadName = threadName;
this.p = p;
this.s = s;
}
public void run() {
int count = 5;
while(count > 0){
synchronized(p){
synchronized(s){
System.out.println("Java Thread" + this.threadName);
count--;
s.notify();
}
try{
p.wait();
}catch(Exception e){
}
}
}
System.exit(0);
}
/********* End *********/
}
练习-Java输入输出之字节数据输入输出之综合练习
import java.io.*;
import java.util.Scanner;
public class FileTest {
public static void main(String[] args) throws IOException {
// 请在Begin-End间编写完整代码
/********** Begin **********/
// 使用字节输出流和输入流,把给定文件里的内容复制到另一个给定文件中
Scanner input = new Scanner(System.in);
String input1 = input.next();
String output = input.next();
FileInputStream fis = new FileInputStream(input1);
FileOutputStream fos = new FileOutputStream(output);
int read = 0;
byte[] buff = new byte[8];
while((read = fis.read(buff)) != -1){
fos.write(buff,0,read);
}
fis.close();
fos.close();
/********** End **********/
}
}
第1关:Java分支结构之 if...else
package step2;
import java.util.Scanner;
public class HelloIfStep2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/******start******/
System.out.println("请输入学员成绩:");
int score = input.nextInt();
if(score>85) {
System.out.println("优,非常棒!");
} else{
System.out.println("良,下次加油!");
}
/******end******/
}
}
第2关:Java分支结构之Switch
package step4;
import java.util.Scanner;
public class HelloSwitch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入月份:");
int input = sc.nextInt(); //获取输入的月份
//通过输入的月份来判断当前季节并输出
/*****start*****/
switch(input){
case 12:
case 1:
case 2:
System.out.print(input + "月是冬天");
break;
case 3:
case 4:
case 5:
System.out.print(input + "月是春天");
break;
case 6:
case 7:
case 8:
System.out.print(input + "月是夏天");
break;
case 9:
case 10:
case 11:
System.out.print(input + "月是秋天");
break;
}
/*****end*****/
}
}
第1关:使用synchronized关键字同步线程
package step2;
public class Task {
public static void main(String[] args) {
final insertData insert = new insertData();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
public void run() {
insert.insert(Thread.currentThread());
}
}).start();
}
}
}
class insertData{
public static int num =0;
/********* Begin *********/
public synchronized void insert(Thread thread){
for (int i = 0; i <= 5; i++) {
num++;
System.out.println(num);
}
}
/********* End *********/
}
第2关:捕获异常
package step2;
import java.util.Scanner;
public class Task {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
/********* Begin *********/
try{
System.out.println(num1/num2);
}catch(Exception e){
System.out.print("除数不能为0");
}
/********* End *********/
}
}
第3关:抛出异常
package step3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Task {
/********* Begin *********/
//请在合适的部位添加代码
public static void main(String[] args) throws FileNotFoundException {
test();
}
public static void test() throws FileNotFoundException {
File file = new File("abc");
if(!file.exists()){ //判断文件是否存在
//文件不存在,则 抛出 文件不存在异常
throw new FileNotFoundException("该文件不存在");
}else{
FileInputStream fs = new FileInputStream(file);
}
}
/********* End *********/
}
第4关:自定义异常
package step4;
import java.util.Scanner;
public class Task {
/********* Begin *********/
public static void main(String[] args) throws MyException{
Scanner sc = new Scanner(System.in);
String username = sc.next();
//判断用户名
if(username.length() < 3 ){
throw new MyException("用户名小于三位Exception");
}else{
System.out.print("用户名格式正确");
}
}
}
class MyException extends Exception{
private static final long serialVersionUID = 1L;
public MyException(){
}
public MyException(String msg){
super(msg);
}
}
/********* End *********/
第1关:初识数组
package step1;
public class HelloWorld {
public static void main(String[] args) {
/********** Begin **********/
int[] scores={91,88,60};
System.out.println("数组的第一个值为:"+scores[0]); //在这里输出数组的第一个值
System.out.println("数组的第二个值为:"+scores[1]); //在这里输出数组的第二个值
System.out.println("数组的第三个值为:"+scores[2]); //在这里输出数组的第三个值
/********** End **********/
}
}
第4关:数组练习-平均值和最大值
package step3;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] scores = new int[sc.nextInt()];
//循环给数组赋值
for(int i = 0 ; i< scores.length;i++){
scores[i] = sc.nextInt();
}
/********** Begin **********/
//在这里计算数组scores的平均值和最大值
int sum=0;
for(int i=0;i<scores.length;i++){
sum+=scores[i];
}
double temp=(double)sum/(double)scores.length;
int t=-1;
for(int i=0;i<scores.length;i++){
if(t<scores[i]){
t=scores[i];
}
}
System.out.println("平均值:" +temp );
System.out.println("最大值:" +t );
/********** End **********/
}
}
第5关:二维数组
package step4;
public class HelloWorld {
public static void main(String[] args) {
/********** Begin **********/
int[][]score={
{92,85},
{91,65},
{90,33}
};
for(int i=0;i<score.length;i++){
for(int j=0;j<score[i].length;j++){
System.out.println(score[i][j]);
}
}
for(int i=0;i<score.length;i++){
score[i][0]=1;
score[i][1]=2;
}
for(int i=0;i<score.length;i++){
for(int j=0;j<score[i].length;j++){
System.out.println(score[i][j]);
}
}
/********** End **********/
}
}
第1关:字符流 - 输入输出
package step3;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Task {
public void task() throws IOException{
/********* Begin *********/
FileReader read = new FileReader("src/step3/input/input.txt");
FileWriter writer = new FileWriter("src/step3/output/output.txt");
char[] buff = new char[1024];
int arr = 0;
while((arr = read.read(buff)) != -1){
writer.write(buff,0,arr);
}
read.close();
writer.close();
/********* End *********/
}
}
字符流输入输出
package step3;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Task {
public void task() throws IOException{
/********* Begin *********/
File file1 = new File("src/step3/input/input.txt");
File file2 = new File("src/step3/output/output.txt");
FileReader fr = new FileReader(file1);
FileWriter fw = new FileWriter(file2);
char[] ch = new char[8];
fr.read(ch);
fw.write(ch);
fr.close();
fw.close();
/********* End *********/
}
}
顺序输出
package step1;
public class Task {
public static void main(String[] args) throws Exception {
/********* Begin *********/
//在这里创建线程, 开启线程
Object a = new Object();
Object b = new Object();
Object c = new Object();
MyThread ta = new MyThread("A",c,a);
MyThread tb = new MyThread("B",a,b);
MyThread tc = new MyThread("C",b,c);
ta.start();
ta.sleep(100);
tb.start();
tb.sleep(100);
tc.start();
tc.sleep(100);
/********* End *********/
}
}
class MyThread extends Thread {
/********* Begin *********/
private String threadName;
private Object prev;
private Object self;
public MyThread(String name,Object prev,Object self){
this.threadName = name;
this.prev = prev;
this.self = self;
}
public void run() {
int count = 5;
while(count>0){
synchronized(prev){
synchronized(self){
System.out.println("Java Thread"+this.threadName+this.threadName);
count--;
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.exit(0);
}
/********* End *********/
}
捕获异常
package step2;
import java.util.Scanner;
public class Task {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
/********* Begin *********/
try{
System.out.println(num1/num2);}
catch(Exception e){
System.out.println("除数不能为0");}
/********* End *********/
}
}
构造方法
package step2;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = sc.next();
String sex = sc.next();
/********** Begin **********/
//分别使用两种构造器来创建Person对象
Person p=new Person();
Person p1=new Person(name,sex)
/********** End **********/
}
//创建Person对象,并创建两种构造方法
/********** Begin **********/
class Person{
String name1;
String sex1;
public Person()
{
System.out.println("一个人被创建了");
}
public Person(String name,String sex)
{ // this.name1=name;
//this.sex1=sex;
System.out.println("姓名:"+ name +",性别:" + sex +",被创建了");
}
/********** End **********/
类与对象练习:
Test:
package step4;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String theMa = sc.next();
int quantity = sc.nextInt();
boolean likeSoup = sc.nextBoolean();
/********** Begin **********/
//使用三个参数的构造方法创建WuMingFen对象 取名 f1
WuMingFen f1 = new WuMingFen(theMa,quantity,likeSoup);
//使用两个参数的构造方法创建WuMingFen对象 取名 f2
WuMingFen f2 = new WuMingFen(theMa,quantity);
//使用无参构造方法创建WuMingFen对象 取名 f3
WuMingFen f3 = new WuMingFen();
//分别调用三个类的 check方法
WuMingFen.check();
/********** End **********/
}
}
Wumingfen:
/********** Begin **********/
//在这里添加包名 step4
package step4;
//创建类 添加属性和方法
public class WuMingFen{
String theMa;
int quantity;
boolean likeSoup;
public WuMingFen(){
this.theMa = theMa;
this.quantity = quantity;
this.likeSoup = likeSoup
}
public WuMingFen(String name,int a,boolean b){
System.out.println("面码:"+name+",粉的份量:"+a+"两,是否带汤:"+b)
}
public WuMingFen(String name,int a){
System.out.println("面码:"+name+",粉的份量:"+a+"两,是否带汤:false");
}
public static void check(){
System.out.println("面码:酸辣,粉的份量:2两,是否带汤:true");
}
}
String类的常用方法
package step1;
public class StringExample {
public static void main(String args[]) { /********* Begin *********/
String s1 = new String("you are a student"),
s2 = new String("how are you");
if (s1.equals(s2)) // 使用equals方法判断s1与s2是否相同
{
System.out.println("s1与s2相同");
} else {
System.out.println("s1与s2不相同");
}
String s3 = new String("22030219851022024");
if (s3.contains("220302")) // 判断s3的前缀是否是“220302”
{
System.out.println("吉林省的身份证");
}
String s4 = new String("你"), s5 = new String("我");
if (s4.compareTo(s5)>0)// 按着字典序s4大于s5的表达式
{
System.out.println("按字典序s4大于s5");
} else {
System.out.println("按字典序s4小于s5");
}
int position = 0;
String path = "c:\\java\\jsp\\A.java";
position = path.lastIndexOf("\\");// 获取path中最后出现\\的位置
System.out.println("c:\\java\\jsp\\A.java中最后出现\\的位置:" + position);
String fileName = path.substring(path.lastIndexOf("\\")+1);// 获取path中“A.java”子字符串
System.out.println("c:\\java\\jsp\\A.java中含有的文件名:" + fileName);
String s6 = new String("100"), s7 = new String("123.678");
int n1 = Integer.parseInt(s6); // 将s6转化成int型数据
double n2 = Double.parseDouble(s7); // 将s7转化成double型数据
double m = n1 + n2;
System.out.println(m);
String s8 = String.valueOf(m); // String调用valueOf(m)方法将m转化为字符串对象
position = s8.indexOf(".");
String temp = s8.substring(position+1); // 获取s8中小数点后面的小数
System.out.println("数字" + m + "有" + temp.length() + "位小数");
String s9 = new String("ABCDEF");
char a[] = s9.toCharArray(); // 将s9存放到数组a中
for (int i = a.length - 1; i >= 0; i--) {
System.out.print(" " + a[i]);
} /********* End *********/
}
}
矩阵转置
package step2;
import java.util.Scanner;
public class SwapMatrix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] matrix = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrix[i][j] = scanner.nextInt();
}
} /********** Begin **********/
System.out.println("原始数组为:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
System.out.println("行列互调后数组为:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(matrix[j][i]+" ");
}
System.out.println();
} /********** End **********/
scanner.close();
}
}
求平均分及各个区间段的人数
package step3;
import java.util.Scanner;
public class Score {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in); /********** Begin **********/
int A=0,B=0,C=0,D=0,E=0;
double sum=0;
double score=scanner.nextDouble();
while(score!=-1){
if(score<60){
E++;
}else if(score<70){
D++;
}else if(score<80){
C++;
}else if(score<90){
B++;
}else {
A++;
}
sum+=score;
score=scanner.nextDouble();}
int total=A+B+C+D+E;
double average=sum/total;
System.out.println("不及格的人数为:"+E);
System.out.println("及格的人数为:"+D);
System.out.println("中等的人数为:"+C);
System.out.println("良好的人数为:"+B);
System.out.println("优秀的人数为:"+A);
System.out.println("全班平均分为:"+String.format("%.1f",average));
/********** End **********/
scanner.close();
}
}
编写一个代表三角形的类
package step1;
import java.util.Scanner;
public class Triangle {
// 自行设计类的实现/********** Begin **********/
private double a;
private double b;
private double c;
public Triangle(double a,double b,double c){
this.a=a;
this.b=b;
this.c=c;
}
public double getA(){
return a;
}
public void setA(double a){
this.a=a;
}
public double getB(){
return b;
}
public void setB(double b){
this.b=b;
}
public double getC(){
return c;
}
public void setC(double c){
this.c=c;
}
public double getarea(){
double s=(a+b+c)/2;
double area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
return area;
}
public double getperi(){
return a+b+c;
}
public String toString(){
return "三角形(" + a + "," + b + "," + c + ")";
} /********** End **********/
public static void main(String[] args) {
/********** Begin **********/
Scanner sc = new Scanner(System.in);
double a,b,c; //定义三条边
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
Triangle t1 = new Triangle(a, b, c);
//输出面积
System.out.println(t1 + "的面积为:" + String.format("%.2f",t1.getarea()));
//输出周长
System.out.println(t1 + "的周长为:" + String.format("%.2f",t1.getperi()));
/********** End **********/
}
}
编写一个圆环类
package step2;
public class Ring { /********** Begin **********/
private double a;
private double b;
private String c;
public Ring(double a,double b,String c){
this.a=a;
this.b=b;
this.c=c;
}
public double getA(){
return a;
}
public void setInnerRadius(double a){
this.a=a;
}
public void setA(double a){
this.a=a;
}
public double getB(){
return b;
}
public void setOuterRadius(double b){
this.b=b;
}
public void setB(double b){
this.b=b;
}
public String getC(){
return c;
}
public void setColor(String c){
this.c=c;
}
public void setC(String c){
this.c=c;
}
public double getarea(){
return Math.PI*(b*b-a*a);
}
public double getperiw(){
return 2*Math.PI*b;
}
public double getperin(){
return 2*Math.PI*a;
} /********** End **********/
public static void main(String[] args) {
Ring ring = new Ring(5, 8, "red");
System.out.println("圆环的内半径: " + ring.getA());
System.out.println("圆环的外半径: " + ring.getB());
System.out.println("圆环的颜色: " + ring.getC());
System.out.println("圆环的面积: " + String.format("%.2f",ring.getarea()));
System.out.println("圆环的外圆周长: " + String.format("%.2f",ring.getperiw()));
System.out.println("圆环的内圆周长: " + String.format("%.2f",ring.getperin()));
System.out.println();
ring.setInnerRadius(4);
ring.setOuterRadius(6);
ring.setColor("blue");
System.out.println("圆环的内半径: " + ring.getA());
System.out.println("圆环的外半径: " + ring.getB());
System.out.println("圆环的颜色: " + ring.getC());
System.out.println("圆环的面积: " + String.format("%.2f",ring.getarea()));
System.out.println("圆环的外圆周长: " + String.format("%.2f",ring.getperiw()));
System.out.println("圆环的内圆周长: " + String.format("%.2f",ring.getperin()));
}
}
编写一个学生类
package step3;
public class Student { /********** Begin **********/
private int num;
private int age;
private String name;
public Student(int num,int age,String name){
this.num=num;
this.age=age;
this.name=name;
}
public int getNum(){
return num;
}
public void setNum(int num){
this.num=num;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age=age;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String toString(){
return "学号:"+num+",姓名:"+name+",年龄:"+age;
} /********** End **********/
public static void main(String args[]) {
Student s1 = new Student(1, 18, "小明");
Student s2 = new Student(2, 20, "小张");
Student s3 = new Student(3, 19, "小李");
Student s4 = new Student(4, 18, "小王");
Student s5 = new Student(5, 20, "小赵");
Student s[] = { s1, s2, s3, s4, s5 }; // 给对象数组赋值
System.out.println("班级学生名单如下:");
output(s); // 第1次调用output方法输出数组
/********** Begin **********/
for(int i=0;i<s.length;i++){ // 将所有学生年龄加1
s[i].age=s[i].age+1;
} /********** End **********/
System.out.println("所有学生年龄加 1 后...");
output(s); /// 第2次调用output方法输出数组
int count = 0;
/********** Begin **********/
for(int i=0;i<s.length;i++){ //统计大于20岁的学生个数
if(s[i].age>20){
count++;
}
}
/********** End **********/
System.out.println("大于 20 岁人数是:" + count);
}
/* 以下方法输岀学生数组的所有元素 */
private static void output(Student s[]) {
for (int i = 0; i < s.length; i++)
System.out.println(s[i]);
}
}
类的继承
package step1;
import java.util.Scanner;
class Person { /********** Begin **********/
private String name; //姓名
private String sex; //性别
private int age; //年龄
public Person(String name, String sex, int age){ //构造方法
this.name = name;
this.sex = sex;
this.age = age;
}
//重写toString()方法
public String toString(){
return name + "," + sex + "," + age;
}
/********** End **********/
}
class Student extends Person {
/********** Begin **********/
private String no; //学号
private String enter; //入学时间
private String major; //专业
public Student(String name, String sex, int age, String no, String enter, String major){
super(name, sex, age);
this.no = no;
this.enter = enter;
this.major = major;
}
public String toString(){ //重写toString()方法
return super.toString() + "," + no + "," + enter + "," + major;
}
/********** End **********/
}
class Teacher extends Person {
/********** Begin ********** // 自行设计类的实现
private String pro; //职称
private String department; //部门
public Teacher(String name, String sex, int age, String pro, String department){
super(name, sex, age);
this.pro = pro;
this.department = department;
}
//重写toString()方法
public String toString(){
return super.toString() + "," + pro + "," + department;
}
/********** End **********/
}
public class Lab3_1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Student student = new Student(sc.next(), sc.next(), sc.nextInt(), sc.next(), sc.next(), sc.next());
Teacher teacher = new Teacher(sc.next(), sc.next(), sc.nextInt(), sc.next(), sc.next());
System.out.println("学生基本信息为:" + student);
System.out.println("教师的信息为:" + teacher);
sc.close();
}
}
上转型对象的使用,多态的特性
package step2;
abstract class Employee {
public abstract double earnings();
}
class YearWorker extends Employee { //重写earnings()方法
/********** Begin **********/
public double earnings(){
return 100000;
}
/********** End **********/
}
class MonthWorker extends Employee { //重写earnings()方法
/********** Begin **********/
public double earnings(){
return 10000*12;
}
/********** End **********/
}
class WeekWorker extends Employee { //重写earnings()方法
/********** Begin **********/
public double earnings(){
return 5000*4*12;
}
/********** End **********/
}
class Company {
Employee[] employees;
double salaries = 0;
Company(Employee[] employees) {
this.employees = employees;
}
public double salariesPay() {
salaries = 0;
//计算salaries
/********** Begin **********/
for(Employee employee:employees){
salaries +=employee.earnings();
}
/********** End **********/
return salaries;
}
}
public class HardWork {
public static void main(String[] args) {
Employee[] employees = new Employee[20];
for (int i = 0; i < employees.length; i++) {
if(i%3==0)
employees[i] = new WeekWorker();
else if(i%3==1)
employees[i] = new MonthWorker();
else if(i%3==2)
employees[i] = new YearWorker();
}
Company company = new Company(employees);
System.out.println("公司年工资总额:" + company.salariesPay());
}
}
接口的使用
package step3;
/********** Begin **********/
// 定义接口
interface Display {
public void display();
}
// 通知类
class Inform implements Display {
public void display() { // 实现 display() 方法
System.out.println("通知内容");
}
}
// 汽车类
class Car implements Display {
public void display() { // 实现 display() 方法
System.out.println("汽车油量");
}
}
// 广告类
class Adervise implements Display {
public void display() { // 实现 display() 方法
System.out.println("广告消息");
}
} /********** End **********/
public class Lab3_3 {
public static void main(String[] args) {
Display[] arr = { new Inform(), new Car(), new Adervise() };
for (Display d : arr) {
d.display();
}
}
}
综合应用—学生信息管理系统
student:
package step4;
public class Student {
/********** Begin **********/
private String sno; // 学号
private String sname; // 姓名
private String sdept; // 系别
public String getSno() {
return sno;}
public void setSno(String sno) {
this.sno = sno;}
public String getSname() {
return sname;}
public void setSname(String sname) {
this.sname = sname;}
public String getSdept() {
return sdept;}
public void setSdept(String sdept) {
this.sdept = sdept;}
@Override
public String toString() {
return "学号: " + sno + " 姓名: " + sname + " 系部: " + sdept;}
/********** End **********/
}
IStudentDAO:
package step4;
public interface IStudentDAO {
/********** Begin **********/
void insertStudent(Student student);
void updateStudent(Student student);
void deleteStudent(String sno);
Student findStudentBySno(String sno);
void displayAllStudent(); /********** End **********/
}
studentDAOlmpl:
package step4;
import java.util.ArrayList;
import java.util.List;
public class StudentDAOImpl implements IStudentDAO {
static List<Student> students = new ArrayList<Student>(); /********** Begin **********/
@Override
public void insertStudent(Student stu) {
// TODO Auto-generated method stub
students.add(stu);
}
@Override
public void deleteStudent(String sno) {
// TODO Auto-generated method stub
for(Student stu:students){
if(stu.getSno().equals(sno)){
students.remove(stu);
break;
}
}
}
@Override
public void updateStudent(Student stu) {
// TODO Auto-generated method stub
for(Student s:students){
if(stu.getSno().equals(s.getSno())){
stu.setSname(s.getSname());
stu.setSdept(s.getSdept());
break;
}
}
}
@Override
public Student findStudentBySno(String sno) {
// TODO Auto-generated method stub
for(Student stu:students){
if(stu.getSno().equals(sno)){
return stu;
}
}
return null;
}
/********** End **********/
/***显示所有学生信息记录参考代*/
@Override
public void displayAllStudent() {
if (students.size() > 0) {
for (Student stu : students) {
System.out.println(stu);
}
}else {
System.out.println("数据库中无学生记录!");
}
}
}
MainClass:
package step4;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StudentDAOImpl studentDAOImpl = new StudentDAOImpl();
//1. 插入学生信息
Student stu = new Student();
stu.setSno(scanner.next());
stu.setSname(scanner.next());
stu.setSdept(scanner.next());
studentDAOImpl.insertStudent(stu);
//2. 显示插入学生信息
System.out.println("1. 插入学生信息如下:");
studentDAOImpl.displayAllStudent();
//3. 更新学生信息
stu.setSname("李四");
stu.setSdept("计算机系");
studentDAOImpl.updateStudent(stu);
System.out.println("2. 更新后学生信息如下:");
System.out.println(studentDAOImpl.findStudentBySno(stu.getSno()));
//4. 删除指定学生信息
System.out.println("3. 删除当前学号学生信息:" + stu.getSno());
studentDAOImpl.deleteStudent(stu.getSno());
System.out.println("学生信息已删除!");
//2. 显示插入学生信息
System.out.println("5. 显示所有学生信息:");
studentDAOImpl.displayAllStudent()
scanner.close();
}
}
实验四:
public ArtFont() {
super("字体设置"); // 设置默认字体
boldStyle = 0;
italicStyle = 0;
underlineStyle = 0;
fontSizeStyle = 10;
fontNameStyle = "宋体";
font = new Font(fontNameStyle, boldStyle + italicStyle, fontSizeStyle);
northPanel = getNorthPanel();
centerPanel = getCenterPanel();
southPanel = getSouthPanel();
// 设置容器;
Container container = getContentPane();
container.setLayout(new BorderLayout());
// 将northPanel添加到窗体的北部
container.add(northPanel, BorderLayout.NORTH);
// 将centerPanel添加到窗体的中部
container.add(centerPanel, BorderLayout.CENTER);
// 将southPanel添加到窗体的南部
container.add(southPanel, BorderLayout.SOUTH);
setSize(500, 300);
// 将窗体位于屏幕的中央
setLocationRelativeTo(null);
setVisible(true);
}
private JPanel getNorthPanel() {
JPanel panel = new JPanel();
label = new JLabel("输入",JLabel.LEFT);
inputText = new JTextField(10);
boldBx = new JCheckBox("粗体");
italicBx = new JCheckBox("斜体");
colorBtn = new JButton("颜色");
JLabel label2 = new JLabel("计Z2008 202062318 盛燕",JLabel.RIGHT);
inputText.addActionListener(this);
colorBtn.addActionListener(this);
boldBx.addItemListener(this);
italicBx.addItemListener(this);
panel.add(label);
panel.add(inputText);
panel.add(boldBx);
panel.add(italicBx);
panel.add(colorBtn);
panel.add(label2);
return panel;
}
private JPanel getCenterPanel() {
JPanel panel = new JPanel();
txtArea = new JTextArea(10, 10);
panel.setLayout(new BorderLayout());
panel.add(new JScrollPane(txtArea), BorderLayout.CENTER);
return panel;
}
private JPanel getSouthPanel() {
JPanel panel = new JPanel();
//获得系统默认字体
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
fontNames = ge.getAvailableFontFamilyNames();
fontType = new JComboBox(fontNames);
//设置字体大小
fontSizes = new String[63];
for (int i = 0; i < fontSizes.length; i++) {
fontSizes[i] = Integer.toString(i+10);
}
fontSize =new JComboBox(fontSizes);
windowStyle =new JComboBox(style);
fontSize.addItemListener(this);
fontType.addItemListener(this);
panel.add(fontType);
panel.add(fontSize);
panel.add(windowStyle);
return panel;
}
public static void main(String args[]) {
ArtFont artFont = new ArtFont();
artFont.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == boldBx) {
if(boldBx.isSelected()){
boldStyle=Font.BOLD;
}else{
boldStyle=Font.PLAIN;
}
} else if (e.getSource() == italicBx) {
if(italicBx.isSelected()){
italicStyle=Font.ITALIC;
}else{
italicStyle=Font.PLAIN;
}
} else if (e.getSource() == fontType) {
fontNameStyle= (String) e.getItem();
} else if (e.getSource() == fontSize) {
fontSizeStyle=Integer.parseInt((String) e.getItem());
} else if (e.getSource() == windowStyle) {
String s = (String) e.getItem();
String className = "";
if (s.equals("Windows显示效果"))
className = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
else if (s.equals("Unix显示效果"))
className = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
else if (s.equals("默认显示效果"))
className = UIManager.getCrossPlatformLookAndFeelClassName();
try {
UIManager.setLookAndFeel(className);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception de) {
System.out.println("Exception happened!");
}
}
font = new Font(fontNameStyle, boldStyle + italicStyle, fontSizeStyle);
txtArea.setFont(font);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == inputText) {
txtArea.setText(inputText.getText());
} else if (e.getSource() == colorBtn) {
colorStyle=JColorChooser.showDialog(this,"请选择一种颜色",colorStyle);
colorBtn.setForeground(colorStyle);
txtArea.setForeground(colorStyle);
}
}
实验6
(1)字节输入/输出流实现数据的保存和读取:
package step1;
import java.io.*;
import java.util.*;
public class SortArray {
public static void main(String[] args) {
/********** Begin **********/
// 创建保存整型数据的数组(数组大小10)
int[] data = new int[10];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < data.length; i++) {
data[i] = sc.nextInt();
}
// 将数组元素按有小到大顺序排列
Arrays.sort(data);
try {
// 创建数据保存文件,如果文件不存在,重新创建
File file = new File("data.txt");
if (!file.exists()) {
file.createNewFile();
}
// 创建FileOutputStream和DataOutputStream 输出流
FileOutputStream fout = new FileOutputStream(file);
DataOutputStream dout = new DataOutputStream(fout);
// 利用输出流向文件中写入数组数据
for(int i=0;i<data.length;i++){
dout.writeInt(data[i]);
} //关闭输出流
dout.close();
// 创建FileInputStream和DataInputStream 输入流
FileInputStream fileInputStream = new FileInputStream(file);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
// 利用输入流从文件读取数据并输出
for (int i = 0; i < data.length; i++) {
System.out.print(dataInputStream.readInt());
if (i != data.length - 1) {
System.out.print("<");
}
}
System.out.println(); //关闭输入流
dataInputStream.close();
} catch (IOException e) {
// 异常处理
System.out.println("读写发生异常");
} /********** End **********/
}
}
(2)输出流实现发送电报:
package step2;
import java.io.*;
import java.util.Scanner;
public class Encrypt {
public static void main(String[] args) throws IOException {
// 创建要发送的电报
Scanner sc = new Scanner(System.in);
String data = sc.next(); // 将电报分割成字符数组
/********** Begin **********/
char[] a = data.toCharArray();
/********** End **********/
// 打开指定存放电报的文件,如果文件不存在,则创建
File file = new File("data.txt");
if(!file.exists()) {
file.createNewFile();
}
// 循环遍历字符数组,将每个字符加密处理
for (int i = 0; i < a.length; i++) {
a[i] = (char) (a[i] ^ 'q');
} // 利用字符输出流FileWriter将加密后的字符数组写入文件中
/********** Begin **********/
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(a, 0, a.length);
fileWriter.flush();
fileWriter.close();
/********** End **********/
// 利用字符输入流FileReader读取文件,将密文输出
/********** Begin **********/
FileReader fileReader = new FileReader(file);
char[] buffer = new char[10];
int x; //保存读取的数据量
System.out.println("密文:");
while ((x = fileReader.read(buffer)) != -1) {
System.out.print(new String(buffer));
}
fileReader.close(); /********** End **********/
// 利用字符输入流FileReader读取文件,将密文转换为明文输出
/********** Begin **********/
FileReader in = new FileReader(file);
System.out.println("\n明文:");
while ((x = in.read(buffer)) != -1) {
for (int i = 0; i < x; i++) {
buffer[i] = (char)(buffer[i] ^ 'q');}
System.out.print(new String(buffer));}
in.close(); /********** End **********/
}
}
(4) 简单tcp通信client:
package step3;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
Server server = new Server();
server.start();
Scanner sc = new Scanner(System.in);
//创建客户端Socket(s),指定服务器端IP地址和端口号
/********** Begin **********/
Socket s = new Socket("127.0.0.1",8080);
/********** end **********/
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
String name = sc.next();
dos.writeUTF(name);
System.out.println(dis.readUTF());
s.close();
}
}
Server:package step3;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread
@Override
public void run() {
try {
//创建服务器端ServerSocket(ss),指定端口号8000
/********** Begin **********/
ServerSocket ss = new ServerSocket(8080);
/********** end **********/
Socket s = ss.accept();
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
dos.writeUTF("你已经连上服务器了,告诉我你的姓名...");
String name = dis.readUTF();
dos.writeUTF("再见:" + name);
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(5) tcp通信实现奇偶判断client:
package step4;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ClientPlus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ServerPlus server = new ServerPlus();
server.start();
try {
//创建客户端Socket(s),指定服务器端IP地址和端口号
/********** Begin **********/
Socket s = new Socket("127.0.0.1", 8080);
/********** end **********/
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
/********** Begin **********/
while (true) {
System.out.println(dis.readUTF());
String num = sc.next();
dos.writeUTF(num);
}
/********** end **********/
} catch (EOFException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
}
Receivethread:package step4;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
class ReceiveThread extends Thread {
DataOutputStream dos;
DataInputStream dis;
Socket s;
public ReceiveThread(Socket s, DataOutputStream dos, DataInputStream dis) {
this.s = s;
this.dos = dos;
this.dis = dis;
}
@Override
public void run() {
try {
dos.writeUTF("请输入一个整数,我知道是奇数还是偶数");
while(true) {
String num = dis.readUTF();
if("-1".equals(num)) {
s.close();
break;}
String result = (Integer.parseInt(num)%2==0)?"偶数":"奇数";
dos.writeUTF(num + "是..." + result);}
} catch (SocketException e) {
try {
s.close();
} catch (IOException e1) {
e1.printStackTrace();}
} catch (IOException e) {
System.out.println("数据读取异常");}
}
}
Serverplus:package step4;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerPlus extends Thread {
@Override
public void run() {
try {
/********** Begin ********** //创建服务器端ServerSocket(ss),指定端口号8000
ServerSocket ss = new ServerSocket(8080);
/********** end **********/
Socket s = ss.accept();
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
ReceiveThread thread = new ReceiveThread(s, dos, dis);
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
学习通作业一:
package lab1;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myscanner = new Scanner(System.in);
System.out.println("请输入姓名:");
String name=myscanner.next();
System.out.println(name+",您好!欢迎学习Java。");
}
}
(2)编写字符界面面板计算器程序package lab2;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myscanner = new Scanner(System.in);
System.out.print("请输入第一个操作数: x=");
double x = myscanner.nextDouble();
System.out.print("请输入第二个操作数: y=");
double y = myscanner.nextDouble();
double sum,sub,mup,chu;
sum=x+y;
sub=x-y;
mup=x*y;
chu=x/y;
System.out.println("运算结果如下:");
System.out.println("x+y="+sum);
System.out.println("x-y="+sub);
System.out.println("x*y="+mup);
System.out.println("x/y="+chu);
}
}
(3)package lab3;
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Scanner myscanner=new Scanner(System.in);
double x,y;
System.out.print("请输入第一个操作数: x=");
x=myscanner.nextDouble();
System.out.print("请输入第二个操作数: y=");
y=myscanner.nextDouble();
double sum,sub,mup,chu;
sum=x+y;
sub=x-y;
mup=x*y;
chu=x/y;
System.out.println("运算结果如下:");
System.out.println(x+"+"+y+"="+sum);
System.out.println(x+"-"+y+"="+sub);
System.out.println(x+"*"+y+"="+mup);
System.out.println(x+"/"+y+"="+chu);
}
}
作业二:(1)计算圆面积周长
package test4;
import java.util.Scanner;
public class circle {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(" ==== 计算圆面积周长 ====");
System.out.println("请输入圆的半径:");
Scanner sc=new Scanner(System.in);
double r=sc.nextDouble();
System.out.println("半径为"+r+"的圆面积: "+String.format("%.2f", getarea(r)));
System.out.println("半径为"+r+"的圆周长: "+String.format("%.2f", getperi(r)));
}
public static double getarea(double r) {
return 3.14*r*r;
}
public static double getperi(double r) {
return 2*3.14*r;
}
}
(2)求矩形面积和周长的程序:
package test4;
import java.util.Scanner;
public class rectangle {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(" ==== 计算矩形面积周长 ====");
System.out.println("请输入矩形的长度:");
Scanner sc=new Scanner(System.in);
double l=sc.nextDouble();
System.out.println("请输入矩形的宽度:");
double b=sc.nextDouble();
System.out.println("长"+l+"宽"+b+"的矩形面积: "+String.format("%.2f", getarea(l,b)));
System.out.println("长"+l+"宽"+b+"的矩形周长: "+String.format("%.2f", getperi(l,b)));
}
public static double getarea(double l,double b) {
return l*b;
}
public static double getperi(double l,double b) {
return 2*(l+b);
}
(3)编程成绩统计程序,要求运行时提示输入逗号分隔的多个成绩分数,然后对这些分数降序排序,并找出最高和最低分,统计平均分。
package test4;
import java.util.Scanner;
import java.util.Arrays;
public class score {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(" ====成绩统计====");
System.out.println("请输入逗号分隔的多个成绩分数(最多1位小数):");
Scanner sc = new Scanner(System.in);
String str =sc.nextLine();
String[] strs=str.split(",");
double is[]=new double[strs.length];
for(int i=0;i<strs.length;i++) {
is[i]=Double.parseDouble(strs[i]);}
System.out.println("按从大到小(降序)排序后的数据:");
Arrays.sort(is);
for(int i=0;i<is.length/2;i++) {
double temp=is[i];
is[i]=is[is.length-1-i];
is[is.length-1-i]=temp;}
for(int i=0;i<is.length;i++) {
System.out.print(is[i]+" ");}
System.out.println();
System.out.println("最高分: "+max(is));
System.out.println("最低分: "+min(is));
System.out.println("平均分: "+String.format("%.2f",aver(is)));}
public static double max(double[] nums) {//最高分
double max=nums[0];
for(int i=0;i<nums.length;i++) {
if(nums[i]>max)
max=nums[i];}
return max;}
public static double min(double[] nums) {//最低分
double min=nums[0];
for(int i=0;i<nums.length;i++) {
if(nums[i]<min)
min=nums[i];}
return min;}
public static double aver(double[] nums) {//平均分
double aver=nums[0],sum = 0;
for(int i=0;i<nums.length;i++) {
sum+=nums[i];}
aver=sum/nums.length;
return aver;
}
}
作业三:GUI整数加法器:
package homeworks;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class IntegerAdder extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private String num1, operator, result;
private boolean startNum2;
private JButton[] numButtons;
private JButton addButton, equalsButton, clearButton;
public IntegerAdder() {
setTitle("整数加法器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 3));
numButtons = new JButton[10];
for (int i = 0; i < numButtons.length; i++) {
numButtons[i] = new JButton(String.valueOf(i));
numButtons[i].addActionListener(this);}
addButton = new JButton("加");
addButton.addActionListener(this);
equalsButton = new JButton("等于");
equalsButton.addActionListener(this);
clearButton = new JButton("清空");
clearButton.addActionListener(this);
clearButton.setPreferredSize(new Dimension(100, 30));
panel.add(numButtons[0]);
panel.add(numButtons[1]);
panel.add(numButtons[2]);
panel.add(numButtons[3]);
panel.add(numButtons[4]);
panel.add(numButtons[5]);
panel.add(numButtons[6]);
panel.add(numButtons[7]);
panel.add(numButtons[8]);
panel.add(numButtons[9]);
panel.add(addButton);
panel.add(equalsButton);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setPreferredSize(new Dimension(0, 30));
topPanel.add(clearButton, BorderLayout.CENTER);
getContentPane().add(topPanel, BorderLayout.NORTH);
getContentPane().add(panel, BorderLayout.CENTER);
pack();
setVisible(true);
num1 = "";
operator = "";
result = "";
startNum2 = false}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < numButtons.length; i++) // 数字按钮
if (e.getSource() == numButtons[i]) {
if (!startNum2) {
num1 += i;
} else {
result += i;}
clearButton.setText("清空");
return;
}
}
// 清空按钮
if (e.getSource() == clearButton) {
num1 = "";
operator = "";
result = "";
startNum2 = false;
clearButton.setText("清空");
}
if (e.getSource() == addButton) { // 加号按钮
operator = "+";
startNum2 = true;
clearButton.setText("清空");
if (e.getSource() == equalsButton) { // 等号按钮
int n1 = Integer.parseInt(num1);
int n2 = Integer.parseInt(result);
int sum = n1 + n2;
clearButton.setText(num1 + operator + result + "=" + sum);
num1 = String.valueOf(sum);
operator = "";
result = "";
startNum2 = false;
}
}
public static void main(String[] args) {
new IntegerAdder();
}
}
(2)package homeworks;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextStyler extends JFrame implements ActionListener {
private JTextArea textArea;
private JCheckBox italicCheck, boldCheck;
private JRadioButton largeRadio, mediumRadio, smallRadio;
public TextStyler() {
setTitle("文本样式"); // 设置窗口属性
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建主面板,并设置布局为 BoxLayout
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
// 创建左侧面板,包含可复选按钮
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
italicCheck = new JCheckBox("斜体");
italicCheck.addActionListener(this);
boldCheck = new JCheckBox("粗体");
boldCheck.addActionListener(this);
leftPanel.add(italicCheck);
leftPanel.add(Box.createVerticalStrut(10));
leftPanel.add(boldCheck);
mainPanel.add(leftPanel);
JPanel rightPanel = new JPanel();// 创建右侧面板,包含单选按钮
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
largeRadio = new JRadioButton("大字号");
largeRadio.addActionListener(this);
mediumRadio = new JRadioButton("中字号");
mediumRadio.addActionListener(this)
smallRadio = new JRadioButton("小字号");
smallRadio.addActionListener(this);
ButtonGroup group = new ButtonGroup();
group.add(largeRadio);
group.add(mediumRadio);
group.add(smallRadio);
rightPanel.add(largeRadio);
rightPanel.add(Box.createVerticalStrut(10));
rightPanel.add(mediumRadio);
rightPanel.add(Box.createVerticalStrut(10));
rightPanel.add(smallRadio);
mainPanel.add(rightPanel);
// 创建文本框,并设置初始字体样式
textArea = new JTextArea("我喜欢C++,\n但我更喜欢Java");
Font font = new Font("黑体", Font.PLAIN, 12);
textArea.setFont(font);
mainPanel.add(textArea);
// 将主面板添加到窗口中,并显示窗口
add(mainPanel);
setVisible(true);}
// 实现 ActionListener 接口中的方法
public void actionPerformed(ActionEvent e) {
Font font;
int size = 0;
int style = Font.PLAIN;
if (e.getSource() == italicCheck) { // 根据选择设置字体样式
style = italicCheck.isSelected() ? style | Font.ITALIC : style & ~Font.ITALIC;
} else if (e.getSource() == boldCheck) {
style = boldCheck.isSelected() ? style | Font.BOLD : style & ~Font.BOLD;
} else if (e.getSource() == largeRadio) {
size = 48;
font = new Font("黑体", style, size);
textArea.setFont(font);
return; // 直接返回,不需要设置字体大小
} else if (e.getSource() == mediumRadio) {
size = 24;
} else if (e.getSource() == smallRadio) {
size = 12;
}font = new Font("黑体", style, size);
textArea.setFont(font);
}
public static void main(String[] args) {
new TextStyler();
}
}
作业四:Java综合编程编写带图形界面的聊天程序
Server
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class Server implements ActionListener {
JTextArea textArea;
JTextField textField;
JButton sendButton;
ServerSocket serverSocket;
List<ClientThread> clients;
public static void main(String[] args) {
new Server().start();
}
public Server() {
JFrame frame = new JFrame("服务器");
JPanel panel = new JPanel(new BorderLayout());
textArea = new JTextArea(20, 60);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(BorderLayout.CENTER, scrollPane);
JPanel bottomPanel = new JPanel(new BorderLayout());
textField = new JTextField(40);
bottomPanel.add(BorderLayout.CENTER, textField);
sendButton = new JButton("发送");
sendButton.addActionListener(this);
bottomPanel.add(BorderLayout.EAST, sendButton);
panel.add(BorderLayout.SOUTH, bottomPanel);
frame.setContentPane(panel);
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void start() {
try {
serverSocket = new ServerSocket(8000);
clients = new ArrayList<ClientThread>();
while (true) {
Socket socket = serverSocket.accept();
ClientThread clientThread = new ClientThread(socket,textArea);
clients.add(clientThread);
clientThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void removeFromClients(ClientThread clientThread) {
clients.remove(clientThread);
}
@Override
public void actionPerformed(ActionEvent event) {
String message = textField.getText();
if (!message.equals("")) {
// 发送消息给所有客户端
for (ClientThread client : clients) {
client.sendToClient("服务器说: " + message);
}
textField.setText("");
}
}
class ClientThread extends Thread {
Socket socket;
DataInputStream dis;
DataOutputStream dos;
JTextArea textArea;
public ClientThread(Socket socket, JTextArea textArea) {
this.socket = socket;
this.textArea = textArea;
try {
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
try {
dos.writeUTF("exit");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendToClient(String message) {
try {
synchronized (this) {
dos.writeUTF(message);
textArea.append(message + "\n"); // 在客户端窗口中显示消息记录
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
String name = dis.readUTF();
textArea.append(name + "连接成功!\n"); // 添加消息提示
while (true) {
String message = dis.readUTF();
if (message.equals("exit")) {
break;}
textArea.append("客户端" + "说: " + message + "\n"); // 在服务器窗口显示消息记录
}
textArea.append(name + "离开了!\n");
removeFromClients(this);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendToAllClients(String message) {
for (ClientThread client : clients) {
try {
synchronized (client) {
if (!this.equals(client)) { // 不要发送给自己
client.sendToClient(message);
}
client.dos.writeUTF(message);
client.textArea.append(message + "\n"); //在客户端窗口显示消息
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Client
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
JTextArea textArea;
JTextField textField;
Socket socket;
DataInputStream dis;
DataOutputStream dos;
public static void main(String[] args){
new Client().start();
}
public Client() {
JFrame frame = new JFrame("客户端");
JPanel panel = new JPanel(new BorderLayout());
textArea = new JTextArea(20, 60);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(BorderLayout.CENTER, scrollPane);
// 添加输入框和发送按钮
JPanel bottomPanel = new JPanel(new BorderLayout());
textField = new JTextField(40);
bottomPanel.add(BorderLayout.CENTER, textField);
JButton sendButton = new JButton("发送");
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
sendMessage();
}
});
bottomPanel.add(BorderLayout.EAST, sendButton);
panel.add(BorderLayout.SOUTH, bottomPanel);
frame.setContentPane(panel);
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void start() {
try {
socket = new Socket("127.0.0.1", 8000);
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
String name = JOptionPane.showInputDialog("请输入你的姓名:");
dos.writeUTF(name);
Thread listenThread = new ListenThread();
listenThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage() {
try {
String message = textField.getText();
if (!message.equals("")) {
dos.writeUTF(message);
// 在聊天记录中显示客户端说的话
textArea.append("客户端说: " + message + "\n");
}
textField.setText("");
} catch (IOException e) {
e.printStackTrace();
}
}
class ListenThread extends Thread {
@Override
public void run() {
try {
while (!socket.isClosed()) {
String message = dis.readUTF();
textArea.append(message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null) dis.close();
if (dos != null) dos.close();
if (socket != null) socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
本文来自博客园,作者:Cloudservice,转载请注明原文链接:https://www.cnblogs.com/whwh/p/18231585,只要学不死,就往死里学!