Java实验(超详细)

目录

      • 实验一 Java编程基础
      • 实验二 面向对象编程
      • 实验三 泛形与集合
      • 实验四 图形用户界面

实验一 Java编程基础

  1. 使用JDK和MyEclipse编译运行Java应用程序;适当添加注释信息,通过javadoc生成注释文档;通过命令行参数传递“Hello world”字符串,并输出,通过JDK和MyEclipse编译运行。记录操作过程。
public class Hello
{
    public static void main(String args[])
    {
        System.out.println("Hello!");
    }
}
  1. 使用JDK和MyEclipse编译Java Applet,并建立HTML文档运行该Applet.打包mypackage,并压缩生成".jar"文件。记录操作过程。
import java.awt.*;
import java.applet.Applet;
public class HelloApplet extends Applet
{
    public void paint(Graphics g)
    {
        g.setColor(Color.red);
        g.drawString("Hello!",20,20);
    }
}
 
<html>
<applet code="HelloApplet.class"  height=100  width=300>
</applet>
</html>
  1. 输出下列数字形式。
    ①n=4
    0 0 0 0
    0 1 1 1
    0 1 2 2
    0 1 2 3
    ② n=4
    1
    1 2 1
    1 2 3 2 1
    1 2 3 4 3 2 1
public class a {
            public static void main(String[] args) {
                int n = 4;
            int[][] nums = new int[n][n];
    
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                        if (i >= j) {
                            nums[i][j] = j;
                        } else {
                            nums[i][j] = i;
                        }
                    }
                }
    
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        System.out.print(nums[i][j] + " ");
                    }
                    System.out.println();
                }
    }
    }
  1. 采用一维数组输出等腰三角形的杨辉三角。
import java.util.Scanner;
public class Yang_Hui_Triangle {
    public static void main(String[] args) {
        Scanner triangle = new Scanner(System.in);
        System.out.println("请输入杨辉三角的层数");
        int i = 0;
        int j = 0;
        int n = 0;
        int k = 0;
        n = triangle.nextInt();
        int arr[] = new int[2000];
        k = 0;
        while (n-- != 0) {
            arr[k++] = 1;
            for (i = k - 2; i >= 1; i--)
                arr[i] += arr[i - 1];
            for (i = 0; i < n; i++)
                System.out.print(" ");
            for (i = 0; i < k; i++) {
                System.out.print(" ");
                System.out.print(arr[i]);
            }
            System.out.print("\n");
 
        }
    }
}
  1. 求二维数组的鞍点,即该位置上的元素在该行上最大,在列上最小。也可能无鞍点。
import java.util.Scanner;
 
public class Two_dimensional_array {
    public static void main(String[] args) {
        int arr[][] = new int[1000][1000];
        int i = 0;
        int j = 0;
        int i_max = 0;
        int j_max = 0;
        int pos = 0;
        int flag = 0;
        Scanner array = new Scanner(System.in);
        System.out.println("请输入二维数组中的行和列");
        i_max = array.nextInt();
        j_max = array.nextInt();
        for (i = 0; i < i_max; i++)
        {
            for(j = 0; j < j_max; j++)
            {
                arr[i][j] = array.nextInt();
            }
        }
        for (i = 0; i < i_max; ++i)
        {
 
            int max = arr[i][0];
            for (j = 1; j < j_max; ++j)
            {
                if (arr[i][j] > max)
                {
                    max = arr[i][j];
                    pos = j;
                }
            }
 
            for (j = 0; j < j_max; ++j)
            {
                if (arr[j][pos]<max)
                {
                    break;
                }
            }
 
            if (j == j_max)
            {
                System.out.println("该鞍点为:"+arr[i][pos]);
                flag = 1;
                break;
            }
        }
        if (0 == flag)
        {
            System.out.println("没有鞍点");
        }
 
    }
}
  1. 判断回文字符串
    回文是一种“从前向后读”和“从后向前读”都相同的字符串。如“rotor”是一个回文字符串。
    程序中使用了两种算法来判断回文字符串:
    算法一:分别从前向后和从后向前依次获得原串str的一个字符ch1、ch2,比较ch1和ch2,如果不相等,则str肯定不是回文串,yes=false,立即退出循环:否则继续比较,直到字符全部比较完,yes的值仍为true,才能肯定str是回文串。
    算法二:将原串str反转成temp串,再比较两串,如果相等则是因文字符串。
import java.util.Scanner;
public class Palindrome_string {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.nextLine();
 
        if (isPalindrome(str)) {
            System.out.println(str + " is a palindrome.");
        } else {
            System.out.println(str + " is not a palindrome.");
        }
    }
 
    public static boolean isPalindrome(String str) {
        int i = 0;
        int j = str.length() - 1;
 
        while (i < j) {
            if (str.charAt(i) != str.charAt(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
    
    
}
 

实验二 面向对象编程

  1. 设计复数类,成员变量包括实部和虚部,成员方法包括实现复数加法、减法、比较、字符串描述、比较是否相等等操作。
public class ComplexNumber {
        double real;
        double imaginary;
    
        public ComplexNumber(double real, double imaginary) {
            this.real = real;
            this.imaginary = imaginary;
        }
    
        public ComplexNumber add(ComplexNumber n) {
            double newReal = this.real + n.real;
            double newImaginary = this.imaginary + n.imaginary;
            return new ComplexNumber(newReal, newImaginary);
        }
    
        public ComplexNumber subtract(ComplexNumber n) {
            double newReal = this.real - n.real;
            double newImaginary = this.imaginary - n.imaginary;
            return new ComplexNumber(newReal, newImaginary);
        }
    
        public boolean equals(ComplexNumber n) {
            return (this.real == n.real && this.imaginary == n.imaginary);
        }
    
    
    
    
}
  1. 设计Teacher类,继承Person类。
public class Person {
     String name;
     int age;
 
    public Person(String name, int age) {
        this.name = name;
        this.age = 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;
    }
        public static void main(String[] args) {
            Teacher teacher = new Teacher("wzr",20, "jit","professor");
            System.out.println("Teacher's name: " + teacher.getName());
            System.out.println("Teacher's age: " + teacher.getAge());
            System.out.println("Teacher's workfor: " + teacher.getworkfor());
            System.out.println("Teacher's title: " + teacher.gettitle());
        }
    
}
 
class Teacher extends Person {
 
    private String workfor;
    private String title;
 
    public Teacher(String name, int age, String workfor, String title) {
        super(name, age);
        this.workfor = workfor;
        this.title = title;
    }
 
    public String getworkfor() {
        return workfor;
    }
 
    public void setworkfor(String workfor) {
        this.workfor = workfor;
    }
 
    public String gettitle() {
        return title;
    }
 
    public void settitle(String title) {
        this.title = title;
    }
 
  
}
  1. 将Person类的成员变量改为出生日期,再设计age()方法求年龄。
public class Person2 {
    String Name;
    char Sex;
    int BirthYear;
    public Person2()
    {
        this.Name=null;
        this.Sex='M';
        this.BirthYear=0;
    }
    public Person2(String Name,char Sex,int BirthYear)
    {
        this.Name=Name;
        this.Sex=Sex;
        this.BirthYear=BirthYear;
    }
    public void age(int BirthYear)
    {
        System.out.println("age is:"+(2023 - BirthYear));
    }
    public void Information()
    {
        System.out.println("Personal Information:");
        System.out.println(Name+"\t"+Sex+"\t");
    }
 
    public static void main(String args[])
    {
        
        Teacher2 T1= new Teacher2();
        T1.Name="ZhangSan";
        T1.Sex='F';
        T1.WorkFor="JIT";
        T1.Title="professor";
        T1.EngagedIn="JAVA";
        T1.BirthYear = 2003;
        T1.Information();
        T1.age(2003);
        
    }
}
class Teacher2 extends Person2{
    String WorkFor;      
    String Title;       
    String EngagedIn;   
    public Teacher2()
    {
        this.WorkFor=null;
        this.Title=null;
        this.EngagedIn=null;
    }
    public Teacher2(String Name,char Sex,int BirthYear,String WorkFor,String Title,String EngagedIn)
    {
        super(Name,Sex,BirthYear);
        this.WorkFor=WorkFor;
        this.Title=Title;
        this.EngagedIn=EngagedIn;
    }
    
    public void age(int BirthYear)
    {
        super.age(BirthYear);
 
    }
    
    public void Information()
    {
        super.Information();
        System.out.println("Work for:"+WorkFor);
        System.out.println("Profession:"+EngagedIn+"\nTitle:"+Title);
        
    }
}
 
  1. 设计圆柱体类和圆椎体类,继承圆类Circle并实现Volume接口,计算表面积和体积。
interface Volume {
    double getVolume();
}
 
class Circle {
    protected double radius;
 
    public Circle(double radius) {
        this.radius = radius;
    }
 
    public double getRadius() {
        return radius;
    }
 
    public double getArea() {
        return Math.PI * radius * radius;
    }
}
 
class Cylinder extends Circle implements Volume {
    protected double height;
 
    public Cylinder(double radius, double height) {
        super(radius);
        this.height = height;
    }
 
    public double getHeight() {
        return height;
    }
 
    public double getVolume() {
        return getArea() * height;
    }
 
    public double getSurfaceArea() {
        return 2 * Math.PI * radius * (radius + height);
    }
}
 
class Cone extends Circle implements Volume {
    protected double height;
 
    public Cone(double radius, double height) {
        super(radius);
        this.height = height;
    }
 
    public double getHeight() {
        return height;
    }
 
    public double getVolume() {
        return (1.0 / 3.0) * getArea() * height;
    }
 
    public double getSurfaceArea() {
        double slantHeight = Math.sqrt(radius * radius + height * height);
        return Math.PI * radius * (radius + slantHeight);
    }
}
  1. 设计三角形类,继承图形抽象类,计算三角形面积和周长。
public class Graph {
    int edge;
    public Graph(int edge)
    {
        this.edge = edge;
    }
    public int getedge()
    {
        return edge;
    }
    public void setedge(int edge)
    {
       this.edge = edge; 
    }
    public static void main(String[] args) {
        
    }
}
 
class Triangle extends Graph{
    int Bottom_edge_length;
     int height;
     public Triangle(int edge,int Bottom_edge_length,int height)
     {
        super(edge);
        this.Bottom_edge_length = Bottom_edge_length;
        this.height = height;
 
     }
 
}
  1. 定义机动车接口(Automobile)和非机动车接口(Nonautomobile),分别包含表示其运动模式的抽象方法;编写总的“车”类(VehicleClass),其中描述车名、车轮数,以及机动车和非机动车变量,该类实现机动车和非机动车接口;编写继承“车”类的公共汽车类(BusClass)和自行车类(BicycleClass)。
interface Automobile {
    void drive();
}
 
interface Nonautomobile {
    void pedal();
}
 
class VehicleClass implements Automobile, Nonautomobile {
    protected String vehicleName;
    protected int wheelCount;
 
    public VehicleClass(String vehicleName, int wheelCount) {
        this.vehicleName = vehicleName;
        this.wheelCount = wheelCount;
    }
 
    public String getVehicleName() {
        return vehicleName;
    }
 
    public int getWheelCount() {
        return wheelCount;
    }
 
    public void drive() {
        System.out.println(vehicleName + " is being driven.");
    }
 
    public void pedal() {
        System.out.println(vehicleName + " is being pedaled.");
    }
}
 
class BusClass extends VehicleClass implements Automobile {
    private int passengerCount;
 
    public BusClass(String vehicleName, int wheelCount, int passengerCount) {
        super(vehicleName, wheelCount);
        this.passengerCount = passengerCount;
    }
 
    public int getPassengerCount() {
        return passengerCount;
    }
 
    public void drive() {
        System.out.println(vehicleName + " is a bus and is being driven.");
    }
}
 
class BicycleClass extends VehicleClass implements Nonautomobile {
    private int gearCount;
 
    public BicycleClass(String vehicleName, int wheelCount, int gearCount) {
        super(vehicleName, wheelCount);
        this.gearCount = gearCount;
    }
 
    public int getGearCount() {
        return gearCount;
    }
 
    public void pedal() {
        System.out.println(vehicleName + " is a bicycle and is being pedaled.");
    }
}
  1. 试编码实现简单的银行业务:处理简单帐户存取款、查询。编写银行帐户类BankAccount,包含数据成员:余额(balance)、利率(interest);操作方法:查询余额、存款、取款、查询利率、设置利率。再编写主类UseAccount,包含main()方法,创建BankAccount类的对象,并完成相应操作。
class BankAccount {
    private double balance;
    private double interest;
 
    public BankAccount(double balance, double interest) {
        this.balance = balance;
        this.interest = interest;
    }
 
    public double getBalance() {
        return balance;
    }
 
    public void deposit(double amount) {
        balance += amount;
        System.out.println("成功存款:" + amount);
    }
 
    public void withdraw(double amount) {
        if (balance >= amount) {
            balance -= amount;
            System.out.println("成功取款:" + amount);
        } else {
            System.out.println("余额不足,取款失败");
        }
    }
 
    public double getInterest() {
        return interest;
    }
 
    public void setInterest(double interest) {
        this.interest = interest;
        System.out.println("成功设置利率:" + interest);
    }
}
 
public class UseAccount {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(1000.0, 0.05);
 
        double balance = account.getBalance();
        System.out.println("当前余额:" + balance);
 
        account.deposit(500.0);
 
        balance = account.getBalance();
        System.out.println("当前余额:" + balance);
 
        account.withdraw(200.0);
 
        balance = account.getBalance();
        System.out.println("当前余额:" + balance);
 
        double interest = account.getInterest();
        System.out.println("当前利率:" + interest);
 
        account.setInterest(0.1);
 
        interest = account.getInterest();
        System.out.println("当前利率:" + interest);
    }
}
  1. 键盘输入两个int数字,并且求出和值。
mport java.util.Scanner;
 
public class ScannerSum{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int result = a + b;
        System.out.println("结果是:"+result);
    }
}
  1. 模拟用户登录。定义用户类,属性为用户名和密码;录入用户和密码,对比用户信息,匹配成功登录成功,否则登录失败。登录失败时,当用户名错误,提示没有该用户。登录失败时,当密码错误时,提示密码有误。
mport java.util.Scanner;
 
public class User {
    private String username;
    private String pwd;
 
    public User(String username, String pwd) {
        this.username = username;
        this.pwd = pwd;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public static void main(String[] args) {
        User[] users = new User[3];
        users[0] = new User("user1", "password1");
        users[1] = new User("user2", "password2");
        users[2] = new User("user3", "password3");
 
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter your username: ");
        String username = scanner.nextLine();
        System.out.print("Please enter your password: ");
        String password = scanner.nextLine();
 
        boolean found = false;
        for (User user : users) {
            if (user.getUsername().equals(username)) {
                found = true;
                if (user.getPwd().equals(password)) {
                    System.out.println("Login successful!");
                    break;
                } else {
                    System.out.println("Password is incorrect!");
                    break;
                }
            }
        }
        if (!found) {
            System.out.println("User not found!");
        }
    }
  1. 把字符串“2023-03-22 16:40:30”转换为时间类型。
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Time {
    public static void main(String[] args) {
        String dateTimeStr= "2023-03-22 16:40:30";
         DateTimeFormatter formatter02 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
         LocalDateTime localDateTime=LocalDateTime.parse(dateTimeStr,formatter02);
         System.out.println(localDateTime);
         String format = localDateTime.format(formatter02);
         System.out.println(format);
 
    }
  1. 生成一个随机100内小数,转换为保留两位小数的字符串,不考虑四舍五入的问题。
import java.text.DecimalFormat;
public class random_number {
        public static void main(String[] args) {
            double d = Math.random()*100;
            DecimalFormat df = new DecimalFormat("0.00");
            String str = df.format(d);
            System.out.println(str);
    
        }
    
  1. 计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?
public class Int {
        public static void main(String[] args) {
            int count = 0;
            double min = - 10.8;
            double max = 5.9;
            for (int i = (int)min; i < max; ++i) {
                if (Math.abs(i) > 6 || Math.abs(i) < 2.1) {
                    if (i % 1 == 0) {
                        count++;
                    }
                }
            }
            System.out.println("There are " + count + " integers the condition.");
        }
  1. 高精度计算1!+2!+3!+……+n! (n<50)
import java.math.BigInteger;
public class FactorialSum {
    public static BigInteger factorial(BigInteger n) {
        if (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE)) {
            return BigInteger.ONE;
        } else {
            return n.multiply(factorial(n.subtract(BigInteger.ONE)));
        }
    }
 
    public static BigInteger calculateFactorialSum(int n) {
        BigInteger sum = BigInteger.ZERO;
        for (int i = 1; i <= n; i++) {
            sum = sum.add(factorial(BigInteger.valueOf(i)));
        }
        return sum;
    }
 
    public static void main(String[] args) {
        int n = 10; 
        BigInteger result = calculateFactorialSum(n);
        System.out.println("1! + 2! + 3! + ... + " + n + "! = " + result);
    }
  1. 编写一个信息录入程序,获取用户输入的姓名和年龄。如果用户输入的年龄不是正确的年龄数字(如0.5),则抛出异常并让用户重新输入;如果年龄正确,则打印用户输入的信息。
import java.util.Scanner;
public class InformationEntry {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        String name;
        int age;
 
        try {
            System.out.print("请输入姓名:");
            name = scanner.nextLine();
 
            System.out.print("请输入年龄:");
            String ageInput = scanner.nextLine();
            age = Integer.parseInt(ageInput);
 
            if (age <= 0) {
                throw new IllegalArgumentException("年龄必须是一个正整数");
            }
 
            System.out.println("姓名:" + name);
            System.out.println("年龄:" + age);
        } catch (NumberFormatException e) {
            System.out.println("年龄输入有误,请输入一个整数年龄");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }

实验三 泛形与集合

  1. 定义一个继承结构:

    属性:名字、年龄
    行为:吃东西

波斯猫方法体打印:一只叫做XXX的,X岁的波斯猫,正在吃小饼干~
狸花猫方法体打印:一只叫做XXX的,X岁的狸花猫,正在吃鱼儿~
泰迪方法体打印:一只叫做XXX的,X岁的泰迪,正在吃骨头,边吃边蹭~
哈士奇方法体打印:一只叫做XXX的,X岁的哈士奇,正在吃骨头,边吃边拆家~
测试类中定义一个方法用于饲养动物
public static void keepPet(ArrayList list) {
// 遍历集合,调用动物的eat方法
}
要求:
a、该方法能养所有品种的猫,但是不能养狗
b、该方法能养所有品种的狗,但是不能养猫
c、该方法能养所有的动物,但是不能传递其他类型

import java.util.ArrayList;
class Animal{
    protected String name;
    protected int age;
    public Animal(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
 
    public void eat() {
        System.out.println("一只叫做" + name + "的" + age + "岁的动物正在吃东西~");
    }
}
class Cat extends Animal{
    public Cat(String name, int age){
        super(name, age);
    }
 
}
class PersianCat  extends Animal{
    public PersianCat (String name, int age){
        super(name, age);
    }
    public void eat() {
        System.out.println("一只叫做" + name + "的" + age + "岁的波斯猫,正在吃小饼干~");
    }
 
}
 class TabbyCat  extends Animal{
    public TabbyCat (String name, int age){
        super(name, age);
    }
    public void eat() {
        System.out.println("一只叫做" + name + "的" + age + "岁的狸花猫,正在吃鱼儿~");
    }
}
class Dog extends Animal{
    public Dog(String name, int age){
        super(name, age);
    }
 
}
class Husky extends Dog {
    public Husky(String name, int age) {
        super(name, age);
    }
    public void eat() {
        System.out.println("一只叫做" + name + "的" + age + "岁的哈士奇,正在吃骨头,边吃边拆家~");
    }
}
class Teddy extends Dog {
    public Teddy(String name, int age) {
        super(name, age);
    }
    public void eat() {
        System.out.println("一只叫做" + name + "的" + age + "岁的泰迪,正在吃骨头,边吃边蹭~");
    }
}
public class AnimalTest {
    public static void keepPet(ArrayList<? extends Animal> list) {
        for (Animal animal : list) {
            animal.eat();
        }
    }
    public static void main(String[] args) {
        ArrayList<Animal> animalList = new ArrayList<>();
        animalList.add(new PersianCat("小白", 2));
        animalList.add(new TabbyCat("小黑", 3));
        animalList.add(new Husky("小花", 1));
        animalList.add(new Teddy("小黄", 2));
        
        keepPet(animalList);
    }
    
    
}
  1. 定义Employee类
    (1)该类包含:private成员变量name,sal,birthday,其中birthday为MyDate类的对象;
    (2)为每一个属性定义getter,setter方法;
    (3)重写toString方法输出name,sal,birthday
    (4)MyDate类包含:private成员变量year,month,year;并为每一个属性定义getter,setter方法;
    (5)创建该类的3个对象,并把这些对象放入ArrayList集合中(ArrayList需使用泛型来定义),对集合中的元素进行排序,并遍历输;
    排序方式:调用ArrayList的sort方法,传入Comparator对象[使用泛型],先按照name排序,如果name相同,则按生日日期的先后排序。
import java.util.ArrayList;
import java.util.Comparator;
class MyDate {
    private int year;
    private int month;
    private int day;
 
    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
 
    public int getYear() {
        return year;
    }
 
    public int getMonth() {
        return month;
    }
 
    public int getDay() {
        return day;
    }
 
    public void setYear(int year) {
        this.year = year;
    }
 
    public void setMonth(int month) {
        this.month = month;
    }
 
    public void setDay(int day) {
        this.day = day;
    }
 
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }
}
 
public class Employee {
    private String name;
    private double sal;
    private MyDate birthday;
 
    public Employee(String name, double sal, MyDate birthday) {
        this.name = name;
        this.sal = sal;
        this.birthday = birthday;
    }
 
    public String getName() {
        return name;
    }
 
    public double getSal() {
        return sal;
    }
 
    public MyDate getBirthday() {
        return birthday;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public void setSal(double sal) {
        this.sal = sal;
    }
 
    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }
 
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday +
                '}';
    }
    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<>();
        employees.add(new Employee("p1", 10000, new MyDate(1990, 1, 1)));
        employees.add(new Employee("p2", 20000, new MyDate(1995, 2, 1)));
        employees.add(new Employee("p3", 15000, new MyDate(1990, 3, 1)));
 
        employees.sort(new Comparator<Employee>() {
            @Override
            public int compare(Employee p1, Employee p2) {
                int nameCompare = p1.getName().compareTo(p2.getName());
                if (nameCompare != 0) {
                    return nameCompare;
                } 
                else {
                    MyDate d1 = p1.getBirthday();
                    MyDate d2 = p2.getBirthday();
                    if (d1.getYear() != d2.getYear()) {
                        return d1.getYear() - d2.getYear();
                    } 
                    else if (d1.getMonth() != d2.getMonth()) 
                    {
                        return d1.getMonth() - d2.getMonth();
                    } else {
                        return d1.getDay() - d2.getDay();
                    }
                }
            }
        });
 
        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }
}

  1. 学者在进行数据统计的时候,为了避免极值的影响,通常会忽略掉最大值和最小值,然后对剩余元素进行统计,请编写程序完成去除极值的工作。
    输入格式:
    一行字符串,数字均为整数,之间使用空格分开(元素个数>=3)。
    输出格式:
    去除两端极值后的剩余元素,升序排列,之间使用空格分开
    输入样例:
    10 3 2 -1 5 3 4 3 0 3 2
    输出样例:
    0 2 2 3 3 3 3 4 5
import java.util.Arrays;
import java.util.Scanner;
public class RemoveExtremun{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        String[] strArray = input.split(" ");
        int[] intArray = new int[strArray.length];
        for (int i = 0; i < strArray.length; i++) {
            intArray[i] = Integer.parseInt(strArray[i]);
        }
        Arrays.sort(intArray);
        for (int i = 1; i < intArray.length - 1; i++) {
            System.out.print(intArray[i] + " ");
        }
    }
  1. 判断e盘下是否有mytemp文件夹,如果没有就创建该文件夹。在该目录下创建文件hello.txt 并写入内容 hello world!如果该文件已存在,提示文件已存在。
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class IsFile {
    public static void main(String[] args) {
        String directoryPath = "/Users/wzr/Desktop";
        String filePath = directoryPath + "/hello.txt";
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
                FileWriter writer = new FileWriter(file);
                writer.write("hello world!");
                writer.close();
                System.out.println("文件已创建并写入内容");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件已存在");
        }
    }
    
}
 
  1. 使用文件字节输入/输出流,合并两个指定文件,合并后的数据要求是已排序的。
import java.io.*;
 
public class MergeAndSortFiles {
    public static void main(String[] args) {
        String file1Path = "file1.txt";  // 第一个文件的路径
        String file2Path = "file2.txt";  // 第二个文件的路径
        String mergedFilePath = "merged.txt";  // 合并后的文件路径
        mergeAndSortFiles(file1Path, file2Path, mergedFilePath);
    }
    public static void mergeAndSortFiles(String file1Path, String file2Path, String mergedFilePath) {
        try {
            FileInputStream file1Input = new FileInputStream(file1Path);
            FileInputStream file2Input = new FileInputStream(file2Path);
            FileOutputStream mergedOutput = new FileOutputStream(mergedFilePath);
            mergeFiles(file1Input, mergedOutput);
            mergeFiles(file2Input, mergedOutput);
            sortFile(mergedFilePath);
            System.out.println("文件合并并排序完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void mergeFiles(FileInputStream input, FileOutputStream output) throws IOException {
        int data;
        while ((data = input.read()) != -1) {
            output.write(data);
        }
        input.close();
    }
 
    public static void sortFile(String filePath) {
        try {
            FileInputStream fileInput = new FileInputStream(filePath);
            DataInputStream dataInput = new DataInputStream(fileInput);
 
            int fileSize = dataInput.available();
            byte[] data = new byte[fileSize];
            dataInput.readFully(data);
            dataInput.close();
            for (int i = 0; i < fileSize - 1; i++) {
                for (int j = 0; j < fileSize - i - 1; j++) {
                    if (data[j] > data[j + 1]) {
                        byte temp = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = temp;
                    }
                }
            }
            FileOutputStream fileOutput = new FileOutputStream(filePath);
            DataOutputStream dataOutput = new DataOutputStream(fileOutput);
            dataOutput.write(data);
            dataOutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用BufferedReader 读取一个文本文件,每行加上一个分号一并输出到屏幕上,并保存到另一个文件中。
import java.io.*;
public class AddSemicolonToFile {
    public static void main(String[] args) {
        String inputFilePath = "input.txt";  
        String outputFilePath = "output.txt";  
 
        addSemicolonToFile(inputFilePath, outputFilePath);
    }
 
    public static void addSemicolonToFile(String inputFilePath, String outputFilePath) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
            FileWriter writer = new FileWriter(outputFilePath);
 
            String line;
            while ((line = reader.readLine()) != null) {
                String modifiedLine = line + ";";  
 
                System.out.println(modifiedLine);  
                writer.write(modifiedLine + "\n");  
            }
 
            reader.close();
            writer.close();
 
            System.out.println("处理完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

实验四 图形用户界面

  1. 计算器设计
import javax.swing.*;
import java.awt.*;
 
public class Calculator extends JFrame {
    public Calculator() {
        JFrame JWindow = new JFrame("计算器");
        JWindow.setBackground(Color.BLACK);
        JWindow.setSize(350,310);
        JWindow.setLocationRelativeTo(null);
        JWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        JWindow.setResizable(false); 
        Font font = new Font("宋体", Font.PLAIN, 20);
        JPanel Panel1 = new JPanel();
        JPanel Panel2 = new JPanel(new GridLayout(4,4,8,12));
        JTextArea JText = new JTextArea(1,16);
        JText.setFont(font);
        JText.setPreferredSize(new Dimension(300,30));
        JText.setEditable(false);
        Panel1.add(JText);
        String BtnStr[] = { "1","2","3","+",
                            "4","5","6","-",
                            "7","8","9","x",
                            ".","0","=","÷"};
        JButton Btn[] = new JButton[BtnStr.length];
        for(int i = 0 ; i < BtnStr.length ; i++ ){
            Btn[i]=new JButton(BtnStr[i]);
            Btn[i].setFont(font);
            Dimension dimension = new Dimension(70,42);
            Btn[i].setPreferredSize(dimension);
            Panel2.add(Btn[i]);
        }
        
        
        JWindow.add(Panel1,BorderLayout.NORTH);
        JWindow.add(Panel2,BorderLayout.CENTER);
        JWindow.setVisible(true);
    }
 
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
    }
}

  1. 整数进制转换
    将一个十进制整数分别转换成二进制、八进制和十六进制整数。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NumberConverterGUI extends JFrame implements ActionListener {
    
    private JLabel decimalLabel, binaryLabel, octalLabel, hexadecimalLabel;
    private JTextField decimalField, binaryField, octalField, hexadecimalField;
    private JButton convertButton;
    
    public NumberConverterGUI() {
        decimalLabel = new JLabel("Decimal:");
        decimalField = new JTextField(10);
        binaryLabel = new JLabel("Binary:");
        binaryField = new JTextField(10);
        octalLabel = new JLabel("Octal:");
        octalField = new JTextField(10);
        hexadecimalLabel = new JLabel("Hexadecimal:");
        hexadecimalField = new JTextField(10);
        convertButton = new JButton("Convert");
        convertButton.addActionListener(this);
        
        JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
        panel.add(decimalLabel);
        panel.add(decimalField);
        panel.add(binaryLabel);
        panel.add(binaryField);
        panel.add(octalLabel);
        panel.add(octalField);
        panel.add(hexadecimalLabel);
        panel.add(hexadecimalField);
        panel.add(new JLabel(""));
        panel.add(convertButton);
        setContentPane(panel);
        
        setTitle("Number Converter");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
    
    public void actionPerformed(ActionEvent e) {
        int decimalNumber = Integer.parseInt(decimalField.getText());
        
        String binaryNumber = Integer.toBinaryString(decimalNumber);
        String octalNumber = Integer.toOctalString(decimalNumber);
        String hexadecimalNumber = Integer.toHexString(decimalNumber);
        
        binaryField.setText(binaryNumber);
        octalField.setText(octalNumber);
        hexadecimalField.setText(hexadecimalNumber);
    }
    
    public static void main(String[] args) {
        new NumberConverterGUI();
    }
}
  1. 模拟裁判评分。
    设计如图所示图形界面,显示n个裁判的评分,根据制定规则计算出最后得分。要求:图形界面采用表格显示裁判评分,随裁判人数变化而变化;指定分数范围,若超出,则异常处理;得分规则有指定接口约定,由多个接口对象给出多种得分规则,如求平均数值,或去掉一个最高分和一个最低分后,再求平均值。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class ScoreChartInterface extends JFrame implements ActionListener {
 
    private List<Double> scores;
    private JLabel scoreLabel, resultLabel;
    private JTextField scoreField;
    private JButton addButton, calculateButton;
 
    interface ScoringRule {
        double calculateScore(List<Double> scores);
    }
 
    class AverageScoringRule implements ScoringRule {
        @Override
        public double calculateScore(List<Double> scores) {
            double sum = 0;
            for (double score : scores) {
                sum += score;
            }
            return sum / scores.size();
        }
    }
 
    class TrimmedAverageScoringRule implements ScoringRule {
        @Override
        public double calculateScore(List<Double> scores) {
            if (scores.size() <= 2) {
                throw new IllegalArgumentException("At least 3 scores are required for trimmed average scoring.");
            }
 
            List<Double> sortedScores = new ArrayList<>(scores);
            Collections.sort(sortedScores);
 
            double sum = 0;
            for (int i = 1; i < sortedScores.size() - 1; i++) {
                sum += sortedScores.get(i);
            }
            return sum / (scores.size() - 2);
        }
    }
 
    public ScoreChartInterface() {
        scores = new ArrayList<>();
 
        scoreLabel = new JLabel("Score:");
        scoreField = new JTextField(10);
        addButton = new JButton("Add");
        addButton.addActionListener(this);
 
        resultLabel = new JLabel("Result: ");
 
        calculateButton = new JButton("Calculate");
        calculateButton.addActionListener(this);
 
        JPanel panel = new JPanel(new GridLayout(4, 1, 10, 10));
        panel.add(scoreLabel);
        panel.add(scoreField);
        panel.add(addButton);
        panel.add(resultLabel);
        panel.add(calculateButton);
        setContentPane(panel);
 
        setTitle("Score Chart");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
 
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == addButton) {
            try {
                double score = Double.parseDouble(scoreField.getText());
                scores.add(score);
                scoreField.setText("");
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "Invalid score format!", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } else if (e.getSource() == calculateButton) {
            if (scores.isEmpty()) {
                JOptionPane.showMessageDialog(this, "No scores available!", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
 
            ScoringRule scoringRule = new AverageScoringRule(); 
            double finalScore = scoringRule.calculateScore(scores);
            resultLabel.setText("Result: " + finalScore);
        }
    }
 
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new ScoreChartInterface();
        });
    }
}

你可能感兴趣的:(Java,java,python,开发语言,学习)