SCAU学习笔记 - 面向对象程序设计课后习题

复活啦!这学期给先给各位带来Java的题解 后续的Bash可能也会有 这篇自己也是边学边敲的 算是共勉啦!

01-基础语法编程的知识点

摄氏温度值度转换成华氏温度值

java.util.Scanner是用来读入数据的,默认读入的是字符串
println输出的时候会自带一个回车,想输出两位小数的话就必须要转成字符串,占位规则和C语言没什么区别
变量的定义和计算赋值啥的都和C语言没啥区别 就不多说了

import java.util.*;

public class one_one {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double C = in.nextDouble();
        double F = C * 9 / 5 + 32;
        System.out.println(String.format("%.2f", F));
    }
}

圆柱体的体积

和上一题没有太大区别

import java.util.*;
import java.lang.*;

public class one_two {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double r = in.nextDouble();
        double h= in.nextDouble();
        double V = Math.PI * r * r * h;
        System.out.println(String.format("%.2f", V));
    }
}

正整数的各位数字之和

nextLine可以直接读取一整行的内容作为字符串存进去
字符串的遍历,包括for循环的语法和取字符串长度都和C++没有差别

import java.util.*;
import java.lang.*;

public class one_three {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        int res=0;
        for(int i=0;i<s.length();i++){
            res+=s.charAt(i)-'0';
        }
        System.out.println(res);
    }
}

三角形的面积

import java.util.*;
import java.lang.*;

public class one_four {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double x1=in.nextDouble();
        double y1=in.nextDouble();
        double x2=in.nextDouble();
        double y2=in.nextDouble();
        double x3=in.nextDouble();
        double y3=in.nextDouble();
        double s1=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
        double s2=Math.sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
        double s3=Math.sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3));
        double s=(s1+s2+s3)/2;
        double area=Math.sqrt(s*(s-s1)*(s-s2)*(s-s3));
        System.out.println(String.format("area=%.2f", area));
    }
}

计算每个月第一天是星期几

开始写一些复杂的逻辑,我们先预处理每个月的天分,把闰年这样一个变量解决了,然后每个月累加天数计算即可

import java.util.*;
import java.lang.*;

public class One_five {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int year = in.nextInt();
        int first = in.nextInt();
        int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            days[1] = 29;
        }
        int[] ans = new int[12];
        ans[0] = first;
        for (int i = 1; i < 12; i++) {
            ans[i] = (ans[i-1] + days[i-1]) % 7;
        }
        for (int i = 0; i < 12; i++) {
            System.out.print(ans[i]);
            if (i != 11) {
                System.out.print(" ");
            }
        }
    }
}

正整数10进制形式转换16进制形式

直接调函数,常见的进制转换一般都有内置函数的

import java.util.*;
import java.lang.*;

public class One_six {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        if(n < 0) {
            System.out.println("不正确的输入");
            return;
        }
        System.out.println(Integer.toHexString(n).toUpperCase());
    }
}

计算自然常数 e 的值

这题要注意一下浮点数和整数的计算规则啥的,如果学过C语言了那就都不成问题吧

import java.util.*;
import java.lang.*;

public class ont_seven {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        if(n < 0) {
            System.out.println("不正确的输入");
            return;
        }
        double e = 1;
        double temp = 1;
        for(int i = 1; i <= n; i++) {
            temp *= i;
            e += 1.0 / temp;
        }
        System.out.println(String.format("%.8f", e));
    }
}

判断回文整数

正常判断回文串即可,注意有负数的话要直接输出错误,所以要取字符串的第一个字符,和C语言有些不同,需要调一个函数

import java.util.*;
import java.lang.*;

public class One_eight {
    public static void main(String[] args) {
        String input = System.console().readLine();
        if(input.charAt(0) == '-') {
            System.out.println("不正确的输入");
            return;
        }
        int len = input.length();
        boolean flag = true;
        for (int i = 0; i < len / 2; i++) {
            if (input.charAt(i) != input.charAt(len - i - 1)) {
                flag = false;
                break;
            }
        }
        if (flag) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}

储物柜问题

注意数组开桶的语法

import java.util.Scanner;

public class One_nine {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m = in.nextInt();
        boolean[] lockers = new boolean[m];
        for (int i = 0; i < m; i++) {
            lockers[i] = false;
        }
        for (int i = 1; i <= m; i++) {
            for (int j = i - 1; j < m; j += i) {
                lockers[j] = !lockers[j];
            }
        }
        for (int i = 0; i < m; i++) {
            if (lockers[i]) {
                System.out.print(i + 1 + " ");
            }
        }
    }
}

考试成绩分析

注意一下长度可变的数组是怎么开的

import java.util.*;
import java.lang.*;

public class One_ten {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[][] arr = new int[n][];
        for (int i = 0; i < n; i++) {
            int m = in.nextInt();
            arr[i] = new int[m];
            for (int j = 0; j < m; j++) {
                arr[i][j] = in.nextInt();
            }
        }

        for (int i = 0; i < n; i++) {
            int sum = 0;
            int max = arr[i][0];
            int min = arr[i][0];
            for (int j = 0; j < arr[i].length; j++) {
                sum += arr[i][j];
                if (arr[i][j] > max) {
                    max = arr[i][j];
                }
                if (arr[i][j] < min) {
                    min = arr[i][j];
                }
            }
            System.out.println(String.format("%.2f %.2f %.2f", (double) sum / arr[i].length, (double) max, (double) min));
        }
    }
}

02-类与对象编程的知识点

终于到类了,作为面向对象编程最重要的概念,我个人浅薄的理解就是自己写像vector那种东西(

了解类的基本结构并定义类

定义类里面的变量就是直接定义就行,然后对这个变量的操作就是在底下写类似C的函数加个public,每个class都类似地看成一个C语言的文件的话,这几个函数就好比是对全局变量做操作,所以不需要传入参数

public class RecTangle {
    double width;
    double height;
    public double getPerimeter() {
        return 2 * (width + height);
    }
    public double getArea() {
        return width * height;
    }
}

掌握构造方法的定义和使用

多个函数同名会看传入的时候的格式和哪个匹配再调用

public class RecTangle {
    double width;
    double height;
    //无参构造方法
    public RecTangle() {
        width = 1;
        height = 1;
    }
    //有参构造方法
    public RecTangle(double w, double h) {
        width = w;
        height = h;
    }
    public double getPerimeter() {
        return 2 * (width + height);
    }
    public double getArea() {
        return width * height;
    }
}

定义类和创建对象求解一元二次方程的根

访问器就是只返回这个值,修改器就是修改值

public class QuadraticEquation {
    double a;
    double b;
    double c;
    //访问器
    public double getA() {
        return a;
    }
    public double getB() {
        return b;
    }
    public double getC() {
        return c;
    }
    //修改器
    public void setA(double newA) {
        a = newA;
    }
    public void setB(double newB) {
        b = newB;
    }
    public void setC(double newC) {
        c = newC;
    }
    public void setAll(double newA, double newB, double newC) {
        a = newA;
        b = newB;
        c = newC;
    }
    
    public double getDiscriminant() {
        return b * b - 4 * a * c;
    }
    
    public double getRoot1() {
        if (getDiscriminant() < 0) {
            return 0;
        } else {
            return (-b + Math.sqrt(getDiscriminant())) / (2 * a);
        }
    }
    public double getRoot2() {
        if (getDiscriminant() < 0) {
            return 0;
        } else {
            return (-b - Math.sqrt(getDiscriminant())) / (2 * a);
        }
    }
}

判断二维坐标系中2个圆的位置关系

函数可以传入另外一个本体,这个时候可以看做C语言里面的结构体可以直接调用出里面定义的全局变量

public class Circle {
    double x,y;
    double radius;
    //无参构造方法
    public Circle() {
        x = 0;
        y = 0;
        radius = 1;
    }
    //有参构造方法
    public Circle(double x, double y, double r) {
        this.x = x;
        this.y = y;
        radius = r;
    }

    boolean contains(Circle other)
    {
        double distance = Math.sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));
        return distance + other.radius <= radius;
    }

    boolean intersects(Circle other)
    {
        double distance = Math.sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));
        return distance <= radius + other.radius;
    }

    boolean separates(Circle other)
    {
        double distance = Math.sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));
        return distance >= radius + other.radius;
    }
}

整数算术四则运算表达式分析程序

用栈实现表达式运算的具体原理可以看我之前写的数据结构的题解
private的意思大概可以理解为只在这个类内部的其他函数可以调用

import java.util.*;

public class ArithmeticExpression {
    String expr;
    //有参构造方法
    public ArithmeticExpression(String expr) {
        this.expr = expr;
    }

    //定义一个map
    public static Map<Character, Integer> getValue = new HashMap<Character, Integer>() {{
        put('+', 1);
        put('-', 1);
        put('*', 2);
        put('/', 2);
    }};

    private void preIni()
    {
        //把括号都变成小括号
        expr = expr.replace('[', '(');
        expr = expr.replace('{', '(');
    }

    public int getResult() {
        preIni();
        String s = expr;
        String parts[] = s.split(" ");
        int l=parts.length;
        //先转为后缀表达式
        Stack<Character> opt = new Stack<>(); //存符号
        Stack<Integer> num = new Stack<>(); //存数字
        ArrayList<Character> all = new ArrayList<>(); //存后缀表达式
        for (int i = 0; i < l; i++) {
            if (parts[i].equals("(")) {
                opt.push('(');
            } else if (parts[i].equals(")")) {
                while (opt.peek() != '(') {
                    all.add(opt.pop());
                }
                opt.pop();
            } else if (parts[i].equals("+") || parts[i].equals("-") || parts[i].equals("*") || parts[i].equals("/")) {
                while (!opt.isEmpty() && getValue.get(opt.peek()) >= getValue.get(parts[i].charAt(0))) {
                    all.add(opt.pop());
                }
                opt.push(parts[i].charAt(0));
            } else {
                all.add(parts[i].charAt(0));
            }
        }
        while (!opt.isEmpty()) {
            all.add(opt.pop());
        }
        //计算后缀表达式
        for (int i = 0; i < all.size(); i++) {
            if (all.get(i) == '+') {
                int a = num.pop();
                int b = num.pop();
                num.push(a + b);
            } else if (all.get(i) == '-') {
                int a = num.pop();
                int b = num.pop();
                num.push(b - a);
            } else if (all.get(i) == '*') {
                int a = num.pop();
                int b = num.pop();
                num.push(a * b);
            } else if (all.get(i) == '/') {
                int a = num.pop();
                int b = num.pop();
                num.push(b / a);
            } else {
                num.push(all.get(i) - '0');
            }
        }
        return num.pop();
    }
}

03-类与对象编程的知识点

初步了解继承

继承就是省得再写一遍和别的类一样的内容

import java.time.LocalDate;

public class Pet {
    private String name;
    private LocalDate birthDate;

    //有参构造方法
    public Pet(String name, LocalDate birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    }

    public void shout()
    {
        System.out.println("名字:" + name + ",生日:" + birthDate.getYear() + "年" + birthDate.getMonthValue() + "月" + birthDate.getDayOfMonth() + "日");
    }
}

public class Cat extends Pet {
    public Cat(String name, LocalDate birthDate) {
        super(name, birthDate);
    }

    public String climbTree()
    {
        return "我会爬树";
    }
}

public class Dog extends Pet {
    public Dog(String name, LocalDate birthDate) {
        super(name, birthDate);
    }

    public String guard()
    {
        return "我会警戒";
    }
}

初步了解方法覆盖

在继承后的子类里面写一个名称与父类有重合的函数会将之前的函数覆盖
注意父类里面是private所以需要写几个取值的函数

import java.time.LocalDate;

public class Pet {
    private String name;
    private LocalDate birthDate;

    //有参构造方法
    public Pet(String name, LocalDate birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    }

    public void shout()
    {
        System.out.println("名字:" + name + ",生日:" + birthDate.getYear() + "年" + birthDate.getMonthValue() + "月" + birthDate.getDayOfMonth() + "日");
    }
    
    public String getName() {
        return name;
    }
    
    public LocalDate getBirthDate() {
        return birthDate;
    }
}

public class Cat extends Pet {
    public Cat(String name, LocalDate birthDate) {
        super(name, birthDate);
    }

    public String climbTree() {
        return "我会爬树";
    }

    //覆盖shout
    public void shout() {
        System.out.println("猫,名字:" + getName() + ",生日:" + getBirthDate().getYear() + "年" + getBirthDate().getMonthValue() + "月" + getBirthDate().getDayOfMonth() + "日");
    }
}

public class Cat extends Pet {
    public Cat(String name, LocalDate birthDate) {
        super(name, birthDate);
    }

    public String climbTree() {
        return "我会爬树";
    }

    //覆盖shout
    public void shout() {
        System.out.println("猫,名字:" + getName() + ",生日:" + getBirthDate().getYear() + "年" + getBirthDate().getMonthValue() + "月" + getBirthDate().getDayOfMonth() + "日");
    }
}

正n多边形类的定义与使用

照着公式抄就行了

import java.lang.*;
import java.util.*;

public class RegularPolygon extends Object{
    private int numberOfSides;
    private double lengthOfSide;
    private double x, y;

    //无参构造函数
    public RegularPolygon() {
        numberOfSides = 3;
        lengthOfSide = 1;
        x = 0;
        y = 0;
    }
    //有参构造函数
    public RegularPolygon(int numberOfSides, double lengthOfSide) {
        this.numberOfSides = numberOfSides;
        this.lengthOfSide = lengthOfSide;
        x = 0;
        y = 0;
    }

    public double getArea() {
        return numberOfSides * lengthOfSide * lengthOfSide / (4 * Math.tan(Math.PI / numberOfSides));
    }

    public double getOffset() {
        return Math.sqrt(x * x + y * y);
    }

    //覆盖 Object 类的 toString 方法,返回 “[边数, 边长]@(x,y)”形式的字符串
    public String toString() {
        return "[" + numberOfSides + ", " + lengthOfSide + "]@(" + x + ", " + y + ")";
    }

    //覆盖 Object 类的 equals 方法,当多边形对象的中心坐标、边数、边长均相同时,返回 true,其他情况返回 false
    public boolean equals(Object obj) {
        if (obj instanceof RegularPolygon) {
            RegularPolygon rp = (RegularPolygon) obj;
            return x == rp.x && y == rp.y && numberOfSides == rp.numberOfSides && lengthOfSide == rp.lengthOfSide;
        }
        return false;
    }

    //覆盖 Object 类的 hashCode方法,要求:r1.equals(r2)返回为true时,r1.hashCode()与r2.hashCode()的返回值相同
    public int hashCode() {
        return Objects.hash(x, y, numberOfSides, lengthOfSide);
    }
}

银行账户类的定义与使用

比较综合地要求实现比较多的功能 一个一个慢慢写 并不难

import java.lang.*;

public class Account{
    private String id;
    private String name;
    private double balance = 0;

    public Account(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public void deposit(double amount) {
        balance += amount;
    }
    public void withdraw(double amount) {
        if (balance >= amount) {
            balance -= amount;
        } else {
            System.out.println("Insufficient balance");
        }
    }

    //覆盖 toString() 方法,返回值形式为:[账号,姓名,余额],金额保留2位小数
    public String toString() {
        return "[" + id + "," + name + "," + String.format("%.2f", balance) + "]";
    }

    //覆盖 equals() 方法,判断两个账户对象相等的依据是两个对象的账号
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof Account) {
            Account account = (Account) obj;
            return this.id.equals(account.id);
        }
        return false;
    }

    //覆盖 hashCode() 方法,根据账户对象的账号来生成哈希值
    public int hashCode() {
        return id.hashCode();
    }

    public String getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public double getBalance() {
        return balance;
    }
}

public class CreditAccount extends Account {
    private double limit;

    public CreditAccount(String id, String name, double limit) {
        super(id, name);
        this.limit = limit;
    }

    //覆盖 Object 类的 toString() 方法,返回值形式为:[账号,姓名,余额,透支额度],金额保留2位小数
    public String toString() {
        return "[" + getId() + "," + getName() + "," + String.format("%.2f", getBalance()) + "," + String.format("%.2f", limit) + "]";
    }

    //编写名为 withdraw 的方法,判断是否可以取款及减少余额。形参 double amount 表示取款金额,返回类型 boolean 表示取款操作是否成
    //功,取款金额超过透支额度时不能取款并返回 false 。即余额不能低于 (-1*信用额度)
    public boolean withdraw(double amount) {
        if (getBalance() - amount >= -limit) {
            super.withdraw(amount);
            return true;
        } else {
            System.out.println("Insufficient balance");
            return false;
        }
    }
}

public class SavingAccount extends Account {
    public SavingAccount(String id, String name) {
        super(id, name);
    }
}

public class AccountManager {
    //accountList,账户数组,一个可以同时存放信用卡账户和储蓄账户对象的数组
    private Account[] accountList;
    //size,表示目前一共有多少个账户(信用卡账户和储蓄账户)
    private int size;
    
    //构造方法,初始化 accountList 数组,数组大小为 10,size 为 0
    public AccountManager() {
        accountList = new Account[10];
        size = 0;
    }
    
    public boolean addAccount(Account account) {
        for(int i = 0; i < size; i++) {
            if(accountList[i].equals(account)) {
                return false;
            }
        }
        if(size == accountList.length) {
            Account[] temp = new Account[accountList.length * 2];
            System.arraycopy(accountList, 0, temp, 0, accountList.length);
            accountList = temp;
        }
        accountList[size++] = account;
        return true;
    }
    
    public boolean removeAccount(Account account) {
        for(int i = 0; i < size; i++) {
            if(accountList[i].equals(account)) {
                accountList[i] = accountList[size - 1];
                accountList[size - 1] = null;
                size--;
                return true;
            }
        }
        return false;
    }
    
    public Account getAccount(String id) {
        for(int i = 0; i < size; i++) {
            if(accountList[i].getId().equals(id)) {
                return accountList[i];
            }
        }
        return null;
    }
    
    public int getTotalBalance() {
        int total = 0;
        for(int i = 0; i < size; i++) {
            total += accountList[i].getBalance();
        }
        return total;
    }
    
    public int getNumberOfCreitAccounts() {
        int count = 0;
        for(int i = 0; i < size; i++) {
            if(accountList[i] instanceof CreditAccount) {
                count++;
            }
        }
        return count;
    }
}

04-Java高级特征的知识点

计算不同形状的零件面积之和

我想创建一个Shape的类组成的数组 但是里面又可能有多种不同的多边形 我们就可以先写一个Shape类然后再从他往下继承就可以啦

import java.util.*;
import java.lang.*;

public abstract class Shape{
    public abstract double getArea();
}

public class Rectangle extends Shape{
    private double width;
    private double height;

    public Rectangle(double width, double height){
        this.width = width;
        this.height = height;
    }

    public double getArea(){
        return width * height;
    }
}

public class Circle extends Shape{
    private double radius;

    public Circle(double radius){
        this.radius = radius;
    }

    public double getArea(){
        return Math.PI * radius * radius;
    }
}

public class Trapezoid extends Shape{
    private double upper;
    private double lower;
    private double height;

    public Trapezoid(double upper, double lower, double height){
        this.upper = upper;
        this.lower = lower;
        this.height = height;
    }

    public double getArea(){
        return (upper + lower) * height / 2;
    }
}

public class CalSumOfSquare {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Shape> shapes = new ArrayList<Shape>();
        while(true)
        {
            String now=sc.nextLine();
            if(now.isEmpty())
                break;
            String[] input = now.split(" ");
            char type = input[0].charAt(0);
            if(type == 'A'){
                double width = Double.parseDouble(input[1]);
                double height = Double.parseDouble(input[2]);
                shapes.add(new Rectangle(width, height));
            }
            else if(type == 'B'){
                double radius = Double.parseDouble(input[1]);
                shapes.add(new Circle(radius));
            }
            else if(type == 'C'){
                double upper = Double.parseDouble(input[1]);
                double lower = Double.parseDouble(input[2]);
                double height = Double.parseDouble(input[3]);
                shapes.add(new Trapezoid(upper, lower, height));
            }
        }
        double sum = 0;
        for(Shape shape : shapes){
            sum += shape.getArea();
        }
        System.out.println(sum);
    }
}

整数加法练习程序

为了方便修改 我们把每道题和每次训练可以封装成一个类

import java.util.*;
import java.lang.*;

public class Problem{
    private int a;
    private int b;

    public Problem(int min,int max)
    {
        Random rand = new Random();
        this.a = rand.nextInt(max-min+1)+min;
        this.b = rand.nextInt(max-min+1)+min;
    }

    public void OutPut(int Id)
    {
        System.out.printf("题目%d: %d + %d = ?, 输入你的答案: ",Id,a,b);
    }

    public boolean Check(int ans)
    {
        return ans == a+b;
    }
}

public class Practise{
    private ArrayList<Problem> problems;
    private int score;

    public Practise(int n,int min,int max)
    {
        problems = new ArrayList<Problem>();
        for(int i=0;i<n;i++)
        {
            problems.add(new Problem(min,max));
        }
        score = 0;
    }

    public void Start()
    {
        Scanner sc = new Scanner(System.in);
        for(int i=0;i<problems.size();i++)
        {
            problems.get(i).OutPut(i+1);
            int ans = sc.nextInt();
            if(problems.get(i).Check(ans))
            {
                System.out.println("正确");
                score++;
            }
            else
            {
                System.out.println("错误");
            }
        }
        System.out.printf("一共做对了 %d 个题目!\n",score);
    }
}

public class PractisePlus {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("输入加法练习的题目数量: ");
        int n = scanner.nextInt();
        System.out.print("输入加法练习的加数范围的最小值: ");
        int min = scanner.nextInt();
        System.out.print("输入加法练习的加数范围的最大值: ");
        int max = scanner.nextInt();
        System.out.printf("本次练习共有%d个题目.\n", n);

        Practise practise = new Practise(n,min,max);
        practise.Start();
    }
}

找出二维坐标系中距离最近和最远的点

用哈希表方便查找

import java.util.*;
import java.lang.*;

public class Point{
    private double x,y;
    public Point(double x, double y){
        this.x = x;
        this.y = y;
    }
    
    public double getX(){
        return x;
    }
    public double getY(){
        return y;
    }
    
    public double getDistance(Point p){
        return Math.sqrt(Math.pow(x-p.x,2)+Math.pow(y-p.y,2));
    }
    
    public boolean equals(Point obj){
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Point point = (Point) obj;
        return Double.compare(point.x, x) == 0 && Double.compare(point.y, y) == 0;
    }
    
    public int hashCode(){
        return Objects.hash(x, y);
    }

    public String toString() {
        return String.format("(%.2f, %.2f)", x, y);
    }
}

public class PointDistance{
    private Set<Point> points;
    public PointDistance(){
        points = new HashSet<>();
    }
    
    public void addPoint(Point p){
        points.add(p);
    }
    
    public Set<Point> getPoints(){
        return points;
    }
    
    public Point[] findClosestPoints(){
        Point[] closestPoints = new Point[2];
        double minDistance = Double.MAX_VALUE;
        for (Point p1 : points){
            for (Point p2 : points){
                if (p1.equals(p2)) continue;
                double distance = p1.getDistance(p2);
                if (distance < minDistance){
                    minDistance = distance;
                    closestPoints[0] = p1;
                    closestPoints[1] = p2;
                }
            }
        }
        return closestPoints;
    }
    
    public Point[] findFarthestPoints(){
        Point[] farthestPoints = new Point[2];
        double maxDistance = Double.MIN_VALUE;
        for (Point p1 : points){
            for (Point p2 : points){
                if (p1.equals(p2)) continue;
                double distance = p1.getDistance(p2);
                if (distance > maxDistance){
                    maxDistance = distance;
                    farthestPoints[0] = p1;
                    farthestPoints[1] = p2;
                }
            }
        }
        return farthestPoints;
    }
}

public class PointCheck {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        PointDistance pd = new PointDistance();

        System.out.print("需要输入的坐标个数: ");
        int n = scanner.nextInt();

        for (int i = 1; i <= n; i++) {
            System.out.printf("第%d个横坐标和纵坐标(x y): ", i);
            double x = scanner.nextDouble();
            double y = scanner.nextDouble();
            pd.addPoint(new Point(x, y));
        }

        Set<Point> points = pd.getPoints();
        System.out.printf("实际共有%d个点\n", points.size());
        System.out.println(points);

        Point[] closestPoints = pd.findClosestPoints();
        Point[] farthestPoints = pd.findFarthestPoints();

        System.out.printf("距离最近: [%s , %s], 距离是: %.2f\n", closestPoints[0], closestPoints[1], closestPoints[0].getDistance(closestPoints[1]));
        System.out.printf("距离最远: [%s , %s], 距离是: %.2f\n", farthestPoints[0], farthestPoints[1], farthestPoints[0].getDistance(farthestPoints[1]));
    }
}

简易产品管理程序

又是熟悉的小课设 真的写起来跟上一章那个银行管理系统差不多

import java.util.*;
import java.lang.*;
import java.time.LocalDate;

public class Product{
    String id;
    String name;
    double price;
    int quantity;
    LocalDate launchDate;

    //无参构造方法
    public Product(){
        id="";
        name="";
        price=0.0;
        quantity=0;
        launchDate=LocalDate.now();
    }

    //有参构造方法
    public Product(String id,String name,double price,int quantity,LocalDate launchDate){
        this.id=id;
        this.name=name;
        this.price=price;
        this.quantity=quantity;
        this.launchDate=launchDate;
    }

    //实现 Comparable 接口,以编号作为比较依据
    public int compareTo(Product p){
        return this.id.compareTo(p.id);
    }

    //实现 Cloneable 接口,要求实现深克隆
    public Product clone(){
        Product p=new Product();
        p.id=this.id;
        p.name=this.name;
        p.price=this.price;
        p.quantity=this.quantity;
        p.launchDate=this.launchDate;
        return p;
    }

    //重写 equals 和 hashCode 方法,以编号作为比较依据和产品哈希值的依据
    public boolean equals(Object obj){
        if(obj==null){
            return false;
        }
        if(this==obj){
            return true;
        }
        if(obj instanceof Product){
            Product p=(Product)obj;
            return this.id.equals(p.id);
        }
        return false;
    }

    public int hashCode(){
        return this.id.hashCode();
    }
}

public class ProductInventory{
    private List<Product> products;

    //无参构造方法
    public ProductInventory(){
        products=new ArrayList<Product>();
    }

    //有参构造方法
    public ProductInventory(List<Product> products){
        this.products=products;
    }

    public Product getProduct(String id){
        for(Product p:products){
            if(p.id.equals(id)){
                return p;
            }
        }
        return null;
    }

    public void addProduct(Product p){
        products.add(p);
    }

    boolean removeProduct(String id){
        for(Product p:products){
            if(p.id.equals(id)){
                products.remove(p);
                return true;
            }
        }
        return false;
    }

    public int getTotalQuantity(){
        int total=0;
        for(Product p:products){
            total+=p.quantity;
        }
        return total;
    }

    public double getTotalAmount(){
        double total=0.0;
        for(Product p:products){
            total+=p.price*p.quantity;
        }
        return total;
    }

    public List<Product> getProducts(){
        return products;
    }
}

public class ProuctManager {
    public int displayMenu(){
        System.out.println("1. Add a product");
        System.out.println("2. Remove a product");
        System.out.println("3. Display total quantity");
        System.out.println("4. Display total amount");
        System.out.println("5. Exit");
        System.out.println("Please select an option:");
        Scanner sc=new Scanner(System.in);
        int option=sc.nextInt();
        return option;
    }

    public void entryProduct()
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Please enter the product id:");
        String id=sc.nextLine();
        System.out.println("Please enter the product name:");
        String name=sc.nextLine();
        System.out.println("Please enter the product price:");
        double price=sc.nextDouble();
        System.out.println("Please enter the product quantity:");
        int quantity=sc.nextInt();
        System.out.println("Please enter the product launch date:");
        String date=sc.nextLine();
        LocalDate launchDate=LocalDate.parse(date);
        Product p=new Product(id,name,price,quantity,launchDate);
        ProductInventory pi=new ProductInventory();
        pi.addProduct(p);
    }

    public void reduceProduct()
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Please enter the product id:");
        String id=sc.nextLine();
        ProductInventory pi=new ProductInventory();
        pi.removeProduct(id);
    }

    public void removeProduct()
    {
        ProductInventory pi=new ProductInventory();
        int total=pi.getTotalQuantity();
        System.out.println("The total quantity is:"+total);
    }

    public void listProuct()
    {
        //1. 按名称升序/2.按价格升序/3.按库存数量降序/0.直接返回,你的选择:
        Scanner sc=new Scanner(System.in);
        System.out.println("1. Sort by name");
        System.out.println("2. Sort by price");
        System.out.println("3. Sort by quantity");
        System.out.println("0. Exit");
        System.out.println("Please select an option:");
        int option=sc.nextInt();
        ProductInventory pi=new ProductInventory();
        List<Product> products=pi.getProducts();
        switch(option){
            case 1:
                Collections.sort(products,new Comparator<Product>(){
                    public int compare(Product p1,Product p2){
                        return p1.name.compareTo(p2.name);
                    }
                });
                break;
            case 2:
                Collections.sort(products,new Comparator<Product>(){
                    public int compare(Product p1,Product p2){
                        return (int)(p1.price-p2.price);
                    }
                });
                break;
            case 3:
                Collections.sort(products,new Comparator<Product>(){
                    public int compare(Product p1,Product p2){
                        return p2.quantity-p1.quantity;
                    }
                });
                break;
            case 0:
                return;
        }
        for(Product p:products){
            System.out.println(p.id+" "+p.name+" "+p.price+" "+p.quantity+" "+p.launchDate);
        }
    }

    void start()
    {
        while(true){
            int option=displayMenu();
            switch(option){
                case 1:
                    entryProduct();
                    break;
                case 2:
                    reduceProduct();
                    break;
                case 3:
                    removeProduct();
                    break;
                case 4:
                    listProuct();
                    break;
                case 5:
                    return;
            }
        }
    }
}

泛型方法的定义和使用

泛型可以看这篇文章
我要说的是extend那里是用来限制这个T必须得是可以比较的数据类型 不然进去之后比较大小是会报错的

import java.util.*;

public class ArrayUtil {

    public static <T> T[] removeDuplicates(T[] array) {
        if (array == null) {
            return null;
        }
        Set<T> set = new HashSet<>(Arrays.asList(array));
        set.remove(null);
        T[] result = Arrays.copyOf(array, set.size());
        int i = 0;
        for (T element : set) {
            result[i++] = element;
        }
        return result;
    }

    public static <T extends Comparable<T>> T max(T[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        T max = array[0];
        for (T element : array) {
            if (element != null && element.compareTo(max) > 0) {
                max = element;
            }
        }
        return max;
    }

    public static <T extends Comparable<T>> T min(T[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        T min = array[0];
        for (T element : array) {
            if (element != null && element.compareTo(min) < 0) {
                min = element;
            }
        }
        return min;
    }
}

泛型类的定义和使用

实现一个队列 就用数组模拟就行了

public class ArrayQueue<T> {
    private T[] queue;
    private int front;
    private int back;
    private int size;
    private int capacity;
    
    public ArrayQueue() {
        this.capacity = 16;
        queue = (T[]) new Object[capacity];
        front = 0;
        back = 0;
        size = 0;
    }
    
    public ArrayQueue(int capacity) {
        if(capacity < 1) {
            throw new IllegalArgumentException("Capacity must be at least 1");
        }
        this.capacity = capacity;
        queue = (T[]) new Object[capacity];
        front = 0;
        back = 0;
        size = 0;
    }
    
    public boolean isEmpty() {
        return size == 0;
    }
    
    public boolean isFull() {
        return size == capacity;
    }
    
    public void add(T item) {
        if(isFull()) {
            throw new IllegalStateException("Queue is full");
        }
        queue[back] = item;
        back = (back + 1) % capacity;
        size++;
    }
    
    public T remove() {
        if(isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        T item = queue[front];
        queue[front] = null;
        front = (front + 1) % capacity;
        size--;
        return item;
    }
}

05-文件管理与输入输出的知识点

显示目录或文件的属性

简单熟悉一下相关的函数就行了 可以看看这篇文章

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;

public class FileAttributes {
    private File file;

    public FileAttributes(String path) {
        this.file = new File(path);
    }

    public boolean isDirectory() {
        return file.isDirectory();
    }

    public boolean isFile() {
        return file.isFile();
    }

    public long getDirectorySize(File dir) {
        long size = 0;
        File[] files = dir.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isFile()) {
                    size += f.length();
                } else {
                    size += getDirectorySize(f);
                }
            }
        }
        return size;
    }

    public int getFileCount(File dir) {
        int count = 0;
        File[] files = dir.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isFile()) {
                    count++;
                } else {
                    count += getFileCount(f);
                }
            }
        }
        return count;
    }

    public int getDirectoryCount(File dir) {
        int count = 0;
        File[] files = dir.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    count++;
                    count += getDirectoryCount(f);
                }
            }
        }
        return count;
    }

    public void printAttributes() {
        if (!file.exists()) {
            System.out.println("该路径不是一个有效的文件或目录。");
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String lastModified = sdf.format(new Date(file.lastModified()));

        if (isDirectory()) {
            System.out.println("目标名称:" + file.getName());
            System.out.println("目标类型:目录");
            System.out.println("所在位置:" + file.getAbsolutePath());
            System.out.println("目录大小:" + getDirectorySize(file) + " 字节");
            System.out.println("修改时间:" + lastModified);
            System.out.println("包含文件:" + getFileCount(file) + " 个");
            System.out.println("包含目录:" + getDirectoryCount(file) + " 个");
            System.out.println("可写:" + file.canWrite());
            System.out.println("可读:" + file.canRead());
            System.out.println("可运行:" + file.canExecute());
            System.out.println("隐藏:" + file.isHidden());
        } else if (isFile()) {
            String fileName = file.getName();
            String extension = "";
            int dotIndex = fileName.lastIndexOf('.');
            if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
                extension = fileName.substring(dotIndex);
            } else {
                extension = "无";
            }
            System.out.println("目标名称:" + fileName);
            System.out.println("目标类型:文件(" + extension + ")");
            System.out.println("所在位置:" + file.getAbsolutePath());
            System.out.println("文件大小:" + file.length() + " 字节");
            System.out.println("修改时间:" + lastModified);
            System.out.println("可写:" + file.canWrite());
            System.out.println("可读:" + file.canRead());
            System.out.println("可运行:" + file.canExecute());
            System.out.println("隐藏:" + file.isHidden());
        }
    }
}

public class FiveOne {
    public static void main(String[] args) {
        System.out.println("请输入一个文件名或目录名:");
        String path = System.console().readLine();
        FileAttributes fileAttributes = new FileAttributes(path);
        fileAttributes.printAttributes();
    }
}

统计Java源程序文件中关键字的使用次数

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;

public class KeywordCounter {
    private List<String> keywords;
    private Map<String, Integer> keywordCounts;

    public KeywordCounter() {
        keywords = new ArrayList<>();
        keywordCounts = new HashMap<>();
        readKeywords();
    }

    private void readKeywords() {
        try (BufferedReader reader = Files.newBufferedReader(Paths.get("keywords.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                keywords.add(line.trim());
                keywordCounts.put(line.trim(), 0);
            }
        } catch (IOException e) {
            System.err.println("读取 keywords.txt 失败: " + e.getMessage());
            System.exit(1);
        }
    }

    public void countKeywordsInFile(File file) {
        try (BufferedReader reader = Files.newBufferedReader(file.toPath())) {
            String line;
            while ((line = reader.readLine()) != null) {
                for (String keyword : keywords) {
                    Pattern pattern = Pattern.compile("\\b" + keyword + "\\b");
                    Matcher matcher = pattern.matcher(line);
                    while (matcher.find()) {
                        keywordCounts.put(keyword, keywordCounts.get(keyword) + 1);
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("读取 Java 源文件失败: " + e.getMessage());
            System.exit(1);
        }
    }

    public void writeKeywordCountsToFile(File file) {
        List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(keywordCounts.entrySet());
        sortedEntries.sort(Map.Entry.comparingByKey());

        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("Keywords-" + file.getName()))) {
            for (Map.Entry<String, Integer> entry : sortedEntries) {
                writer.write(entry.getKey() + ": " + entry.getValue());
                writer.newLine();
            }
        } catch (IOException e) {
            System.err.println("写入关键字计数到文件失败: " + e.getMessage());
        }
    }

    public void printTopKeywords(int topN) {
        List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(keywordCounts.entrySet());
        sortedEntries.sort((e1, e2) -> {
            int cmp = e2.getValue().compareTo(e1.getValue());
            if (cmp == 0) {
                return e1.getKey().compareTo(e2.getKey());
            }
            return cmp;
        });

        for (int i = 0; i < topN && i < sortedEntries.size(); i++) {
            Map.Entry<String, Integer> entry = sortedEntries.get(i);
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

简易地址簿管理程序

最复杂的一个课设了 完结撒花喵

import java.io.Serializable;
import java.util.List;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Address implements Serializable {
    private String name;
    private String province;
    private String city;
    private String postalCode;
    private String detailedAddress;

    public Address(String name, String province, String city, String postalCode, String detailedAddress) {
        this.name = name;
        this.province = province;
        this.city = city;
        this.postalCode = postalCode;
        this.detailedAddress = detailedAddress;
    }

    public String getName() {
        return name;
    }

    public String getProvince() {
        return province;
    }

    public String getCity() {
        return city;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public String getDetailedAddress() {
        return detailedAddress;
    }

    @Override
    public String toString() {
        return "姓名: " + name + ", 省份: " + province + ", 城市: " + city + ", 邮政编码: " + postalCode + ", 详细地址: " + detailedAddress;
    }
}

public class AddressBook implements Serializable {
    private List<Address> addresses;

    public AddressBook() {
        addresses = new ArrayList<>();
    }

    public void addAddress(Address address) {
        addresses.add(address);
    }

    public List<Address> findAddressesByName(String name) {
        List<Address> result = new ArrayList<>();
        for (Address address : addresses) {
            if (address.getName().equalsIgnoreCase(name)) {
                result.add(address);
            }
        }
        return result;
    }

    public boolean removeAddress(Address address) {
        return addresses.remove(address);
    }

    public void updateAddress(Address oldAddress, Address newAddress) {
        int index = addresses.indexOf(oldAddress);
        if (index != -1) {
            addresses.set(index, newAddress);
        }
    }

    public void listAllAddresses() {
        for (Address address : addresses) {
            System.out.println(address);
        }
    }

    public void saveToFile(String fileName) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
            oos.writeObject(this);
        } catch (IOException e) {
            System.err.println("保存地址簿失败: " + e.getMessage());
        }
    }

    public static AddressBook loadFromFile(String fileName) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
            return (AddressBook) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("读取地址簿失败: " + e.getMessage());
            return new AddressBook();
        }
    }
}

public class LastDance {
    private static final String FILE_NAME = "address_book.dat";

    public static void main(String[] args) {
        AddressBook addressBook = AddressBook.loadFromFile(FILE_NAME);
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("请选择操作:");
            System.out.println("1. 列出所有地址");
            System.out.println("2. 增加新地址");
            System.out.println("3. 查找地址");
            System.out.println("4. 删除地址");
            System.out.println("5. 修改地址");
            System.out.println("6. 退出并保存");

            int choice = scanner.nextInt();
            scanner.nextLine(); // consume newline

            switch (choice) {
                case 1:
                    addressBook.listAllAddresses();
                    break;
                case 2:
                    System.out.println("请输入姓名:");
                    String name = scanner.nextLine();
                    System.out.println("请输入省份:");
                    String province = scanner.nextLine();
                    System.out.println("请输入城市:");
                    String city = scanner.nextLine();
                    System.out.println("请输入邮政编码:");
                    String postalCode = scanner.nextLine();
                    System.out.println("请输入详细地址:");
                    String detailedAddress = scanner.nextLine();
                    addressBook.addAddress(new Address(name, province, city, postalCode, detailedAddress));
                    break;
                case 3:
                    System.out.println("请输入要查找的姓名:");
                    String searchName = scanner.nextLine();
                    List<Address> foundAddresses = addressBook.findAddressesByName(searchName);
                    for (Address address : foundAddresses) {
                        System.out.println(address);
                    }
                    break;
                case 4:
                    System.out.println("请输入要删除的姓名:");
                    String deleteName = scanner.nextLine();
                    List<Address> addressesToDelete = addressBook.findAddressesByName(deleteName);
                    if (addressesToDelete.isEmpty()) {
                        System.out.println("未找到地址。");
                    } else {
                        for (int i = 0; i < addressesToDelete.size(); i++) {
                            System.out.println((i + 1) + ". " + addressesToDelete.get(i));
                        }
                        System.out.println("请选择要删除的地址编号:");
                        int deleteIndex = scanner.nextInt() - 1;
                        scanner.nextLine(); // consume newline
                        if (deleteIndex >= 0 && deleteIndex < addressesToDelete.size()) {
                            addressBook.removeAddress(addressesToDelete.get(deleteIndex));
                        } else {
                            System.out.println("无效的编号。");
                        }
                    }
                    break;
                case 5:
                    System.out.println("请输入要修改的姓名:");
                    String updateName = scanner.nextLine();
                    List<Address> addressesToUpdate = addressBook.findAddressesByName(updateName);
                    if (addressesToUpdate.isEmpty()) {
                        System.out.println("未找到地址。");
                    } else {
                        for (int i = 0; i < addressesToUpdate.size(); i++) {
                            System.out.println((i + 1) + ". " + addressesToUpdate.get(i));
                        }
                        System.out.println("请选择要修改的地址编号:");
                        int updateIndex = scanner.nextInt() - 1;
                        scanner.nextLine(); // consume newline
                        if (updateIndex >= 0 && updateIndex < addressesToUpdate.size()) {
                            Address oldAddress = addressesToUpdate.get(updateIndex);
                            System.out.println("请输入新的姓名(留空则不修改):");
                            String newName = scanner.nextLine();
                            System.out.println("请输入新的省份(留空则不修改):");
                            String newProvince = scanner.nextLine();
                            System.out.println("请输入新的城市(留空则不修改):");
                            String newCity = scanner.nextLine();
                            System.out.println("请输入新的邮政编码(留空则不修改):");
                            String newPostalCode = scanner.nextLine();
                            System.out.println("请输入新的详细地址(留空则不修改):");
                            String newDetailedAddress = scanner.nextLine();

                            Address newAddress = new Address(
                                    newName.isEmpty() ? oldAddress.getName() : newName,
                                    newProvince.isEmpty() ? oldAddress.getProvince() : newProvince,
                                    newCity.isEmpty() ? oldAddress.getCity() : newCity,
                                    newPostalCode.isEmpty() ? oldAddress.getPostalCode() : newPostalCode,
                                    newDetailedAddress.isEmpty() ? oldAddress.getDetailedAddress() : newDetailedAddress
                            );
                            addressBook.updateAddress(oldAddress, newAddress);
                        } else {
                            System.out.println("无效的编号。");
                        }
                    }
                    break;
                case 6:
                    addressBook.saveToFile(FILE_NAME);
                    System.out.println("地址簿已保存。");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效的选择。");
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值