Java基础练习4

  • 在这里插入图片描述
import java.util.Arrays;
import java.util.Scanner;

public class Test8_36 {
    public static void main(String[] args) {
        //1. 输出提示长度输入语句并从控制台获取,赋值给int对象n
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number n: ");
        int n = input.nextInt();
        //2. 声明二维数组,长度为n*n
        int[][] arr = new int[n][n];
        //3. 新建一个int型对象,赋值为65+n(规定输入范围)
        int limit_max = 65 + n;
        //4. 输出提示语句,新建一个String型对象用于临时保存
        System.out.println("Enter "+ n + " rows of letters separated by spaces: ");
        char temp_str;
        int temp_int = 0;
        //5. 遍历空二维数组,将输入数据转为int型判断是否合法再赋值
        for (int i = 0 ; i < n ; i++){
            for (int j = 0 ; j < n ; j++){
                temp_str = input.next().charAt(0);
                temp_int = (int) temp_str;
                if (temp_int >= 65 && temp_int < limit_max){
                    arr[i][j] = temp_int;
                } else {
                    System.out.println("Wrong input: the letters must be from A to " + (char)(limit_max - 1));
                    return;
                }
            }
        }
        //6. 两次遍历二维数组,元素作为一维数组下标,判断是否重复+7. 根据结果输出
        int[] count = new int[65 + n];
        for (int i = 0 ; i < n ; i++){
            Arrays.fill(count, 0);
            for (int j = 0 ; j < n ; j++){
                if (count[arr[i][j]] == 0){
                    ++count[arr[i][j]];
                } else {
                    System.out.println("The input array is not Latin square");
                    return;
                }
            }
        }
        for (int j = 0 ; j < n ; j++){
            Arrays.fill(count, 0);
            for (int i = 0 ; i < n ; i++){
                if (count[arr[i][j]] == 0){
                    ++count[arr[i][j]];
                } else {
                    System.out.println("The input array is not Latin square");
                    return;
                }
            }
        }
        System.out.println("The input array is Latin square");
    }
}

  • 在这里插入图片描述
public class Test8_18 {
    public static void main(String[] args) {
        //1. 主方法:矩阵m创建声明赋值
        int[][] m = {{1,2}, {3,4}, {5,6}, {7,8}, {9,10}};
        //2. 主方法:调用shuffle方法,传入矩阵m
        shuffle(m);
    }
    public static void shuffle(int[][] m){
        //3. shuffle方法:声明一个一维数组,长度为2
        int[] temp = new int[2];
        //4. shuffle方法:双层循环中,使用Math.random()与条件判断函数结合随机抽取哪些需要打乱
        for (int a = 0 ; a < m.length ; a++){
            for (int b = 0 ; b < m.length ; b++){
                if ( (int)(Math.random()*2) == 0){      // 交换可能性为50%
                    //交换行
                    temp[0] = m[a][0];
                    temp[1] = m[a][1];
                    m[a][0] = m[b][0];
                    m[a][1] = m[b][1];
                    m[b][0] = temp[0];
                    m[b][1] = temp[1];
                }
            }
        }
    }
}

  • 在这里插入图片描述
import java.util.Arrays;
import java.util.Random;

public class Test6 {
    public static void main(String[] args) {
        // new一个100 000个数字的数组
        int[] arr = new int[100000];
        Random rd = new Random();
        for (int i = 0 ; i < arr.length ; i++){
            arr[i] = rd.nextInt(100000);
        }
        // 计时
        Test6_StopWatch sw = new Test6_StopWatch();
        Arrays.sort(arr);
        sw.stop();
        // 输出结果
        System.out.println("执行了" + sw.getElaspsedTime() + "毫秒");
    }
}
class Test6_StopWatch {
    private long startTime, endTime;

    public Test6_StopWatch(){
        startTime = System.currentTimeMillis();
    }

    public void stop(){
        this.endTime = System.currentTimeMillis();
    }

    public long getElaspsedTime(){
        return this.endTime - this.startTime;
    }
}



  • 在这里插入图片描述
public class Test8 {
    public static void main(String[] args) {
        Test8_Fan fan0 = new Test8_Fan();
        fan0.setSpeed(Test8_Fan.FAST);
        fan0.setradius(10);
        fan0.setColor("yellow");
        fan0.setOn(true);

        Test8_Fan fan1 = new Test8_Fan();
        fan1.setSpeed(Test8_Fan.MEDIUM);
        fan1.setradius(5);
        fan1.setColor("blue");
        fan1.setOn(false);

        System.out.println(fan0.toString());
        System.out.println(fan1.toString());
    }
}

class Test8_Fan {
    static final int SLOW = 1, MEDIUM = 2, FAST = 3;

    private int speed = SLOW;

    private boolean on = false;

    private double radius  = 5;

    String color = "blue";

    // getter and setter

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public boolean isOn() {
        return on;
    }

    public void setOn(boolean on) {
        this.on = on;
    }

    public double getradius() {
        return radius;
    }

    public void setradius(double radius) {
        this.radius = radius;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    // 无参构造方法
    public Test8_Fan(){}

    // 返回字符串
    public String toString(){
        if (on) {
            return speed + " " + color + " " + radius;
        } else {
            return "fan is off";
        }
    }
}

  • 在这里插入图片描述
public class Test9 {
    public static void main(String[] args) {
        Test9_RegularPolygon rp0 = new Test9_RegularPolygon();
        Test9_RegularPolygon rp1 = new Test9_RegularPolygon(6,4);
        Test9_RegularPolygon rp2 = new Test9_RegularPolygon(10, 4, 5.6, 7.8);

        System.out.printf("第一个参数周长、面积:%.2f %.2f\n", rp0.getPerimeter(), rp0.getArea());
        System.out.printf("第二个参数周长、面积:%.2f %.2f\n", rp1.getPerimeter(), rp1.getArea());
        System.out.printf("第三个参数周长、面积:%.2f %.2f\n", rp2.getPerimeter(), rp2.getArea());
    }
}
class Test9_RegularPolygon {
    private int n = 3;
    private double side = 1.0;
    private double x = 0.0;
    private double y = 0.0;

    // 无参构造方法
    public Test9_RegularPolygon(){}
    // 有参构造方法1
    public Test9_RegularPolygon(int n, double side){
        this.n = n;
        this.side = side;
    }
    // 有参构造方法2
    public Test9_RegularPolygon(int n, double side, double x, double y){
        this.n = n;
        this.side = side;
        this.x = x;
        this.y = y;
    }

    // getter and setter

    public int getN() {
        return n;
    }

    public void setN(int n) {
        this.n = n;
    }

    public double getSide() {
        return side;
    }

    public void setSide(double side) {
        this.side = side;
    }

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }

    // 返回周长的getPerimeter方法
    public double getPerimeter(){
        return n * side;
    }

    // 返回面积
    public double getArea(){
        return (n * side * side) / (4 * Math.tan(Math.PI / n));
    }
}

  • 在这里插入图片描述
import java.util.Scanner;

public class Test10 {
    public static void main(String[] args) {
        // 用户输入
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a, b, c: ");
        int a = input.nextInt(), b = input.nextInt(), c = input.nextInt();

        // 创建对象+调用构造方法
        Test10_QuadraticEquation qe = new Test10_QuadraticEquation(a, b, c);

        // 获取判别式结果
        double judge = qe.getDiscriminant();

        if (judge > 1){
            System.out.printf("%.3f %.3f\n", qe.getRoot1(), qe.getRoot2());
        } else if (judge < 0.0001 && judge > -0.0001){
            System.out.printf("%.3f\n", qe.getRoot1());
        } else {
            System.out.printf("The equation has no roots");
        }
    }
}
class Test10_QuadraticEquation {
    private double a, b, c;
    // 构造方法
    public Test10_QuadraticEquation(int a, int b, int c){
        this.a = a;
        this.b = b;
        this.c = c;
    }
    // getter方法
    public double getA() {
        return a;
    }
    public double getB() {
        return b;
    }
    public double getC() {
        return c;
    }
    // getDiscriminant方法
    public double getDiscriminant(){
        return b * b - 4 * a * c;
    }
    // 获取两根
    public double getRoot1(){
        return (-b + Math.sqrt(getDiscriminant())) / (2 * a);
    }
    public double getRoot2(){
        return (-b - Math.sqrt(getDiscriminant())) / (2 * a);
    }
}

在这里插入图片描述

import java.util.Scanner;

public class Test13 {
    public static void main(String[] args) {
        // 定义数组
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of rows and columns in the array:");
        int rows = input.nextInt(), cols = input.nextInt();
        double[][] arr = new double[rows][cols];

        // 数组赋值
        System.out.println("Enter the array:");
        for (int a = 0 ; a < rows ; a++){
            for (int b = 0 ; b < cols ; b++){
                arr[a][b] = input.nextDouble();
            }
        }

        // 调用找最大值方法
        Test13_Location l = new Test13_Location();
        l = locateLargest(arr);

        // 输出结果
        System.out.println("The location of the largest elements is " + Test13_Location.maxValue +
                " at (" + Test13_Location.row + ", " + Test13_Location.column + ")");
    }

    public static Test13_Location locateLargest(double[][] a){
        Test13_Location l = new Test13_Location();
        for (int m = 0 ; m < a.length ; m++){
            for (int n = 0 ; n < a[0].length ; n++){
                if (Test13_Location.maxValue < a[m][n]){
                    Test13_Location.maxValue = a[m][n];
                    Test13_Location.row = m;
                    Test13_Location.column = n;
                }
            }
        }
        return l;
    }
}
class Test13_Location {
    public static int row = 0, column = 0;
    public static double maxValue = 0.0;
}
  • 在这里插入图片描述
public class Test1 {
    public static void main(String[] args) {
        // 第一个对象
        Test1_Time t1 = new Test1_Time();
        System.out.printf("%d小时%d分%d秒\n", t1.getHour(), t1.getMinute(), t1.getSecond());
        // 第二个对象
        Test1_Time t2 = new Test1_Time(555550000L);
        System.out.printf("%d小时%d分%d秒", t2.getHour(), t2.getMinute(), t2.getSecond());
    }
}
class Test1_Time {
    // 任务1
    long hour, minute, second;
    // 任务2
    public Test1_Time(){
        long[] arr = millis_to_hms(System.currentTimeMillis());
        hour = arr[0];
        minute = arr[1];
        second = arr[2];
    }
    // 任务3
    public Test1_Time(Long l){
        long[] arr = millis_to_hms(l);
        hour = arr[0];
        minute = arr[1];
        second = arr[2];
    }
    // 指定的时分秒
    public Test1_Time(long hour, long minute, long second){
        this.hour = hour;
        this.minute = minute;
        this.second = second;
    }
    // getter
    public long getHour() {
        return hour;
    }
    public long getMinute() {
        return minute;
    }
    public long getSecond() {
        return second;
    }
    // setTime
    public void setTime(long elapseTime){
        long[] arr = new long[3];
        arr = millis_to_hms(elapseTime);
        hour += arr[0];
        minute += arr[1];
        second += arr[2];
    }
    // 计算时分秒
    public long[] millis_to_hms(long l){
        long[] feedback = new long[3];
        feedback[2] = l / 1000 % 60;
        feedback[1] = l / 1000 / 60 % 60;
        feedback[0] = l / 1000 / 60 / 60 % 24;
        return feedback;
    }
}

在这里插入图片描述

public class Test3 {
    public static void main(String[] args) {
        Test3_MyInteger mi = new Test3_MyInteger(1);

        System.out.println(mi.getValue());

        System.out.println(mi.isEven() + " " + mi.isOdd() + " " + mi.isPrime());

        System.out.println(Test3_MyInteger.isEven(2) + " " + Test3_MyInteger.isOdd(2) +
                " " + Test3_MyInteger.isPrime(2));

        Test3_MyInteger mi_pro = new Test3_MyInteger(2);
        System.out.println(Test3_MyInteger.isEven(mi_pro) + " " + Test3_MyInteger.isOdd(mi_pro) +
                " " + Test3_MyInteger.isPrime(mi_pro));

        char[] ch = {'1', '2', '3'};
        System.out.println(Test3_MyInteger.parseInt(ch));

        String str = "123";
        System.out.print(Test3_MyInteger.parseInt(str));
    }
}

class Test3_MyInteger {
    // int型数据域
    static int value;
    // 有参构造方法
    public Test3_MyInteger(int num){
        value = num;
    }
    // 获取value
    public int getValue() {
        return value;
    }
    // 三个方法,判断对象中的值
    public boolean isEven(){
        return value % 2 == 0;
    }
    public boolean isOdd(){
        return value % 2 == 1;
    }
    public boolean isPrime(){
        return havePrimeNumber(value);
    }
    // 判断指定值(int型)
    public static boolean isEven(int num){
        return num % 2 == 0;
    }
    public static boolean isOdd(int num){
        return num % 2 == 1;
    }
    public static boolean isPrime(int num){
        return havePrimeNumber(value);
    }
    // 判断指定值(MyInteger型)
    public static boolean isEven(Test3_MyInteger mi){
        return mi.isEven(mi.value);
    }
    public static boolean isOdd(Test3_MyInteger mi){
        return mi.isOdd(mi.value);
    }
    public static boolean isPrime(Test3_MyInteger mi){
        return havePrimeNumber(mi.value);
    }
    // +: 判断一个数是否是素数
    public static boolean havePrimeNumber(int num){
        boolean bool = true;
        for (int i = 2 ; i <= num / 2 ; i++){
            if (num % i != 0){
                bool = false;
            }
        }
        return bool;
    }
    // 判断值是否相等
    public boolean equals(int num){
        return value == num;
    }
    public boolean equals(Test3_MyInteger mi){
        return this.value == mi.value;
    }
    // 数组字符构成的数组转为int值
    public static int parseInt(char[] arr){
        int length = arr.length;
        String str = "";
        for (int i = 0 ; i < length ; i++){
            str += arr[i];
        }
        return parseInt(str);
    }
    // 字符串转int
    public static int parseInt(String str){
        int length = str.length(), result = 0;
        char temp;
        for (int i = 0 ; i < length ; i++){
            temp = str.charAt(i);
            result = result * 10 + temp - 48;
        }
        return result;
    }
}

  • 在这里插入图片描述
public class Test4 {
    public static void main(String[] args) {
        Test4_MyPoint mp = new Test4_MyPoint();
        System.out.println(mp.distance(10, 30.5));
        // 优化输出:
        System.out.printf("%.4f", mp.distance(10, 30.5));
    }
}

class Test4_MyPoint {
    // 坐标
    double x, y;
    // 无参构造方法
    public Test4_MyPoint(){
        x = 0;
        y = 0;
    }
    // 有参构造方法
    public Test4_MyPoint(double x, double y){
        this.x = x;
        this.y = y;
    }
    // distance方法:到MyPoint类
    public double distance(Test4_MyPoint mp){
        return Math.sqrt((mp.x - this.x) * (mp.x - this.x) + (mp.y - this.y) * (mp.y - this.y));
    }
    // distance方法:到两个坐标值
    public double distance(double x, double y){
        return Math.sqrt((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y));
    }
}

  • 在这里插入图片描述
public class Test10 {
    public static void main(String[] args) {
        Test10_Queue queue = new Test10_Queue();
        for (int i = 1 ; i <= 20 ; i++){
            queue.enqueue(i);
        }
        for (int i = 1 ; i <= 20 ; i++){
            System.out.print(queue.dequeue()+ " ");
        }
    }
}

class Test10_Queue {
    private int[] element;
    private int size = 0;

    public Test10_Queue(){
        element = new int[8];
    }

    public void enqueue(int v){
        if (size == element.length){
            element = enlarge(element);
        }
        element[size] = v;
        size++;
    }
    public int[] enlarge(int[] arr){
        int[] temp = new int[size * 2];
        for (int i = 0 ; i < size ; i++){
            temp[i] = arr[i];
        }
        arr = temp;
        return arr;
    }

    public int dequeue(){
        int temp = element[0];
        System.arraycopy(element, 1, element, 0, size);
        if (size == element.length){
            element[size--] = 0;
        }
        return temp;
    }

    public boolean empty(){
        boolean bool = false;
        if (element[0] == 0){
            bool = true;
        }
        return bool;
    }

    public int getSize(){
        // 这里的队列没有指代清楚到底是队列中含有元素的多少还是容量
        // 这里我处理为队列中元素的数量
        return size;
    }
}

  • 在这里插入图片描述
public class Test11 {
    public static void main(String[] args) {
        Test11_Circle2D c1 = new Test11_Circle2D(2, 2, 5.5);
        System.out.printf("面积:%.2f\n", c1.getArea());
        System.out.printf("周长:%.2f\n", c1.getPerimeter());
        System.out.println("====================");
        System.out.println(c1.contains(3, 3));
        System.out.println(c1.contains(new Test11_Circle2D(4, 5, 10.5)));
        System.out.println(c1.overlaps(new Test11_Circle2D(3, 5, 2.3)));
    }
}

class Test11_Circle2D {
    double x, y;
    public double getX() {
        return x;
    }
    public double getY() {
        return y;
    }

    double radius;
    public double getRadius(){
        return radius;
    }

    public Test11_Circle2D(){
        x = 0;
        y = 0;
        radius = 1;
    }

    public Test11_Circle2D(double x, double y, double radius){
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

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

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

    public boolean contains(double x, double y){
        double distance = Math.sqrt((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y));
        boolean b;
        if (distance >= radius)
            b = false;
        else
            b = true;
        return b;
    }

    public boolean contains(Test11_Circle2D circle){
        // 步1:circle圆心在本圆中
        // 步2:圆心距离+circle半径 <= 本圆半径
        boolean judgeStepOne, judgeStepTwo;
        double distance = Math.sqrt((x - circle.x) * (x - circle.x) + (y - circle.y) * (y - circle.y));
        judgeStepOne = contains(circle.x, circle.y);
        judgeStepTwo = (distance + circle.radius <= radius);
        return judgeStepOne && judgeStepTwo;
    }

    public boolean overlaps(Test11_Circle2D circle){
        // 圆心距离小于两半径和
        double distance = Math.sqrt((x - circle.x) * (x - circle.x) + (y - circle.y) * (y - circle.y));
        return distance < radius + circle.radius;
    }
}

  • 在这里插入图片描述
public class Test22_MyString1 {
    char[] ch;
    public Test22_MyString1(char[] chars){
        ch = chars;
    }
    public char charAt(int index){
        return ch[index];
    }

    public int length(){
        return ch.length;
    }

    public Test22_MyString1 substring(int begin, int end){
        char[] feedback = new char[end - begin];
        for (int i = 0 ; begin < end ; i++){
            feedback[i] = ch[begin];
            begin++;
        }
        return new Test22_MyString1(feedback);
    }

    public Test22_MyString1 toLowerCase(){
        int temp = 0;
        for (int i = 0 ; i < ch.length ; i++){
            temp = ch[i];
            if (temp >= 65 && temp <= 90){
                temp += 32;
                ch[i] = (char) temp;
            }
        }
        return new Test22_MyString1(ch);
    }

    public boolean equals(Test22_MyString1 s){
        boolean result = true;
        // 比较长度
        int thisLength = ch.length;
        int sLength = s.ch.length;
        if (thisLength != sLength)
            return false;
        // 比较内容
        for (int i = 0 ; i < thisLength ; i++){
            if (ch[i] != s.ch[i]){
                result = false;
            }
        }
        return result;
    }

    public static Test22_MyString1 valueOf(int i){
        // 这里我理解的是将i转为Test22_MyString1类型,i作为字符传入
        char[] feedback = {(char) i};
        return new Test22_MyString1(feedback);
    }
}

  • 在这里插入图片描述
public class Test23_MyString2 {
    char[] ch;
    // 构造方法
    public Test23_MyString2(String s){
        ch = new char[s.length()];
        for (int i = 0 ; i < s.length() ; i++){
            ch[i] = s.charAt(i);
        }
    }
    // 比较自己数组(其实是字符串),和s的区别
    public int compare(String s){
        // 这里我的理解是比较ch和s有多少个相同字符
        int count = 0;
        int chLen = ch.length;
        int sLen = s.length();
        if (chLen != sLen){
            return 0;
        }
        for (int i = 0 ; i < chLen ; i++){
            if (ch[i] == s.charAt(i)){
                count++;
            }
        }
        return count;
    }
    // 截取子串
    public Test23_MyString2 substring(int begin){
        String feedback = "";
        for (; begin < ch.length ; begin++){
            feedback += ch[begin];
        }
        return new Test23_MyString2(feedback);
    }

    public Test23_MyString2 toUpperCase(){
        int temp = 0;
        for (int i = 0 ; i < ch.length ; i++){
            temp = ch[i];
            if (temp >= 98 && temp <= 133){
                temp -= 33;
                ch[i] = (char) temp;
            }
        }
        String feedback = "";
        for (int i = 0 ; i < ch.length ; i++){
            feedback += ch[i];
        }
        return new Test23_MyString2(feedback);
    }

    public char[] toChars(){
        return ch;
    }

    public static Test23_MyString2 valueOf(boolean b){
        return new Test23_MyString2((b)?"1":"0");
    }
}

  • 在这里插入图片描述
public class Test02 {
    public static void main(String[] args) {
        // 创建多个对象并调用toString方法
        Test02_Person p = new Test02_Person();
        System.out.println(p.toString());

        Test02_Student stu = new Test02_Student();
        System.out.println(stu.toString());

        Test02_Employee e = new Test02_Employee();
        System.out.println(e.toString());

        Test02_Faculty f = new Test02_Faculty();
        System.out.println(f.toString());

        Test02_Staff staff = new Test02_Staff();
        System.out.println(staff.toString());
    }
}
import java.util.GregorianCalendar;

class Test02_MyDate {
    int year, month, day;   // 月从0开始

    public Test02_MyDate(){
        GregorianCalendar gc = new GregorianCalendar();
        year = gc.get(GregorianCalendar.YEAR);
        month = gc.get(GregorianCalendar.MONTH);
        day = gc.get(GregorianCalendar.DAY_OF_MONTH);
    }

    public Test02_MyDate(long l){
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(l);
        year = gc.get(GregorianCalendar.YEAR);
        month = gc.get(GregorianCalendar.MONTH);
        day = gc.get(GregorianCalendar.DAY_OF_MONTH);
    }

    public Test02_MyDate(int year, int month, int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public void setDate(long elapsedTime){
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(elapsedTime + toCalender(year, month, day));
        year = gc.get(GregorianCalendar.YEAR);
        month = gc.get(GregorianCalendar.MONTH);
        day = gc.get(GregorianCalendar.DAY_OF_MONTH);
    }
    public long toCalender(int year, int month, int day){
        day += year * 365;
        switch (month){
            case 11: day += 31;
            case 10: day += 30;
            case 9: day += 31;
            case 8: day += 30;
            case 7: day += 31;
            case 6: day += 31;
            case 5: day += 30;
            case 4: day += 31;
            case 3: day += 30;
            case 2: day += 31;
            case 1: day += 28;
        }
        return (long) day * 24 * 60 * 60 * 1000;
    }
}
class Test02_Person {
    int name, address, phoneNumber, email;

    // 重写toString方法
    @Override
    public String toString(){
        return "Test02_Person -- " + name;
    }
}
class Test02_Student extends Test02_Person{
    static String dayi = "freshman";
    static String daer = "sophomore";
    static String dasan = "junior";
    static String dasi = "senior";

    // 重写toString方法
    @Override
    public String toString(){
        return "Test02_Student -- " + name;
    }
}

import java.util.Date;

class Test02_Employee extends Test02_Person{
    // 办公室
    String office;
    // 工资
    int salary;
    // 受聘日期
    Date dateOfEmploy;
    // 为受聘日期创建一个对象
    public static void main(String[] args) {
        Test02_MyDate my = new Test02_MyDate();
    }

    // 重写toString方法
    @Override
    public String toString(){
        return "Test02_Employee -- " + name;
    }
}

import java.util.Date;

class Test02_Faculty extends Test02_Employee{
    // 办公时间
    Date workTime;
    // 级别
    int level;
    // 重写toString方法
    @Override
    public String toString(){
        return "Test02_Faculty -- " + name;
    }
}
class Test02_Staff extends Test02_Employee{
    // 头衔
    String title;
    // 重写toString方法
    @Override
    public String toString(){
        return "Test02_Staff -- " + name;
    }
}




  • 在这里插入图片描述
import java.util.Arrays;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;

public class Test01 {
    // 测试程序
    public static void main(String[] args) {
        // 提示用户输入三条边、颜色、是否填充的boolean值
        Scanner input = new Scanner(System.in);
        System.out.print("输入三条边的值:");
        int side1 = input.nextInt(), side2 = input.nextInt(), side3 = input.nextInt();
        System.out.print("输入颜色:");
        String color = input.next();
        System.out.print("是否填充(boolean值):");
        boolean filled = input.nextBoolean();
        // 设置以上属性,注意判断三条边能否创建一个三角形且值全部大于0【隐藏条件】
        if ( !isTriangle(side1, side2, side3) ){
            System.out.println("输入的三条边不符合要求");
            System.exit(0);
        }
        /**方法1:直接new子类【推荐使用】*/
        Test01_Triangle myTri = new Test01_Triangle(side1, side2, side3);
        myTri.setColor(color);
        myTri.setFilled(filled);
        // 显示面积、周长、颜色、是否填充
        System.out.println(myTri.getArea() + "\n" + myTri.getPerimeter() + "\n"
                + myTri.getColor() + "\n" + myTri.isFilled());
        /**方法2:多态【不推荐使用,但可以深化语法,了解】*/
        Test01_GeometricObject myGO = new Test01_Triangle(side1, side2, side3);
        myGO.setColor(color);
        myGO.setFilled(filled);
        //如何显示面积和周长:将myGO强转为Test01_Triangle
        /**System.out.println(((Test01_Triangle) myGO).getArea() + "\n" + ((Test01_Triangle) myGO).getPerimeter() + "\n"
                + myTri.getColor() + "\n" + myTri.isFilled());*/
    }
    public static boolean isTriangle(double s1, double s2, double s3){
        // 将三条边传入数组,使用Arrays类的sort方法排序
        // 最短的两条边长度小于第三条边
        double[] arr = {s1, s2, s3};
        Arrays.sort(arr);
        boolean re1 = arr[0] + arr[1] > arr[2];
        boolean re2 = (s1 > 0) && (s2 > 0) && (s3 > 0);
        return re1 && re2;
    }
}


class Test01_GeometricObject {
    // 三个数据域
    String color;
    boolean filled;
    Date dateCreated;

    // 无参构造方法
    public Test01_GeometricObject(){
        dateCreated = new Date();
    }
    // 有参构造方法
    public Test01_GeometricObject(String color, boolean filled){
        this.color = color;
        this.filled = filled;
        dateCreated = new Date();
    }

    // getter and setter 颜色值
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }

    // getter and setter filled
    public boolean isFilled() {
        return filled;
    }
    public void setFilled(boolean filled) {
        this.filled = filled;
    }

    // 获取DateCreated
    public Date getDateCreated() {
        return dateCreated;
    }

    // toString
    @Override
    public String toString() {
        return "Test01_GeometricObject{" +
                "color='" + color + '\'' +
                ", filled=" + filled +
                ", dateCreated=" + dateCreated +
                '}';
    }
}

class Test01_Triangle extends Test01_GeometricObject{
    // 3个数据域
    public double side1 = 1;
    public double side2 = 1;
    public double side3 = 1;

    // 无参构造
    public Test01_Triangle(){
    }
    // 有参构造
    public Test01_Triangle(double side1, double side2, double side3){
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    // 访问器方法
    public double getSide1() {
        return side1;
    }
    public double getSide2() {
        return side2;
    }
    public double getSide3() {
        return side3;
    }

    // 返回三角形面积的getArea()
    public double getArea(){
        double s = (side1 + side2 + side3) / 2;
        return Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);
    }

    // 返回三角形周长
    public double getPerimeter(){
        return side1 + side2 + side3;
    }

    // 返回该三角形的字符串描述
    @Override
    public String toString(){
        return "Triangle: side1 = " + side1 + " side2 = " + side2 + " side = " + side3;
    }
}

  • 在这里插入图片描述
public int arrayPairSum(int[] nums) {
        int min = 0;
     //调用Arrays方法,进行升序排序
        Arrays.sort(nums);
        for(int i = 0;i<nums.length;i += 2) min += nums[i]; 
        return min;
    }
  • 在这里插入图片描述
class Solution {
    public int[] sortArrayByParity(int[] A) {
        int i=0;
        int j=A.length-1;
        while(i<j){
            if(A[i]%2==0){
                i++;
            }else if(A[j]%2==1){
                j--;
            }else{
                int temp=0;
                temp=A[i];
                A[i]=A[j];
                A[j]=temp;
                i++;
                j--;
            }
        }
        return A;
    }
}

  • 在这里插入图片描述
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestDemo {
 public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> ret  = new ArrayList<>();

        if(numRows == 0) {
            return ret;
        }
        List<Integer> oneRow = new ArrayList<>();
        ret.add(oneRow);
        ret.get(0).add(1);//第一行的元素 添加了一个1
        //直接从第2行开始进行计算
        for (int i = 1; i < numRows; i++) {
            List<Integer> curRow = new ArrayList<>();
            curRow.add(1);//当前行的第一个元素
            List<Integer> prevRow = ret.get(i-1);//前一行
            for(int j = 1; j < i;j++) {
                //[i,j] = [i-1,j] +[i-1,j-1]
                int x = prevRow.get(j);
                int y = prevRow.get(j-1);
                curRow.add(x+y);
            }
            //最后一个元素
            curRow.add(1);
            ret.add(curRow);
        }
        return ret;
    }



  public static void main(String[] args) {
       List<List<Integer>> lists = generate(3);
       for (List<Integer> tmp:lists) {
            System.out.println(tmp);
            }
        }
}

  • 在这里插入图片描述
public boolean isToeplitzMatrix(int[][] matrix) {
    for(int i=0;i<matrix.length-1;i++){
        for(int j=0;j<matrix[0].length-1;j++){
            if(matrix[i][j] != matrix[i+1][j+1]){
                return false;
            }
        }
    }
    return true;
}

  • 在这里插入图片描述
private static int[] f3(int[] nums, int target)
	{
		HashMap<Integer, Integer> map = new HashMap<>();
		
		for(int i = 0; i < nums.length; i++)
		{
			int a = target - nums[i];
			map.put(nums[i], i);
			if(map.containsKey(a) && map.get(a) != i)
				return new int [] {map.get(a), i};
		}
		
		throw new IllegalArgumentException("No two sum solution");
	}

在这里插入图片描述

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int result=0;
        int count=0;
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]==1)
            {
                count++;
            }else
            {
                if(count>result)
                {
                    result=count;
                }
                count=0;
            }
        }
        //关键之处,如果一直到末尾一直是连1的话,会导致result没有更新
        return result>count ? result:count;
    }
}
  • 在这里插入图片描述
var plusOne = function(digits) {
 
    let len = digits.length;
    // 从后面往前遍历数组,判断9的情况
    for(let i = len-1;i>=0;i--){
        if(digits[i] == 9){
            digits[i] = 0;
        }else{
            digits[i] ++;
            return digits;
        }     
    }
    // 如果全部都是9,建立新的数组
    let newDigits = [1].concat(digits);
    return newDigits;     
};
  • 在这里插入图片描述
		package array;
public class array1 {
    public static void main(String[] args) {
        int[] ary = {0, 2, 1, -6, 6, -7, 9, 1, 2, 0, 1};
        int[] ary1 = {0, -6, 1, 2, 6, -7, 9, 1, 2, 0, 1};
        int sum = 0;
        for (int i = 0; i < ary.length; i++) {
            sum += ary[i];
        }
        int avg = sum / 3;
        if (avg * 3 != sum) {
            System.out.println("false");
        }
        int temp = 0;
        int step = 0;
        for (int j = 0; j < ary.length; j++) {
            temp += ary[j];
            System.out.print(ary[j] + " ");
            if (temp == avg) {
                temp = 0;
                System.out.println("   ");
                step++;
            }
        }
        if (step == 3) {
            System.out.println("true");
        }
    }
}	
  • 在这里插入图片描述
import java.util.Arrays;

/**
 思路:用一个二维数组来不同取值来控制前进,设置变动的边界为改变的条件
 */
public class Test13 {
    public static void main(String[] args) {
        int[][] arr = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        System.out.println(Arrays.toString(spiralOrder(arr)));
    }
    public static int[] spiralOrder(int[][] arr) {
        if(arr.length == 0)
            return new int[] {};
        //变量top,bottom,left,right分别为上下左右的边界
        int top = 0;
        int bottom = arr.length - 1;
        int left = 0;
        int right = arr[0].length - 1;
        //move为位置数组,move[0]代表行的位移量,move[1]代表列的位移量
        int[] move = new int[]{0,1};
        //index指示结果数组result
        int index = 0;
        //count为数组arr的总元素用于控制循环
        int count = arr.length*arr[0].length;
        //保存结果的数组
        int[] result = new int[arr.length*arr[0].length];
        //arr数组的行列坐标分别用row和column表示
        int row = 0;
        int column = 0;
        while(count > 0) {
            result[index++] = arr[row][column];
            count--;
            if(row == top && column == right && move[1] == 1) { //第三个条件是区别是开始,还是结束的时候
                move[0] = 1;                    //遇到右上角向下转
                move[1] = 0;
                top++;
            } else if(row == bottom && column == right && move[0] == 1) { //遇到右下角向左转
                move[0] = 0;
                move[1] = -1;
                right--;
            } else if(row == bottom && column == left && move[1] == -1) { //遇到左下角向上转
                move[0] = -1;
                move[1] = 0;
                bottom--;
            } else if(row == top && column == left && move[0] == -1) { //遇到左上角向右转
                move[0] = 0;
                move[1] = 1;
                left++;
            }
            //数组arr按规则移动
            row += move[0];
            column += move[1];
        }
        //返回保存好的数组
        return result;
    }
}


  • 在这里插入图片描述
class RecentCounter {
    int count;
    public RecentCounter() {
        this.count=0;
    }
     Queue<Integer> queue=new LinkedList<>();
    public int ping(int t) {
        int c=0;
          queue.offer(t);
        Queue<Integer> myqueue=new LinkedList<>(queue);
       
      
        while(!myqueue.isEmpty()){
            int x=myqueue.poll();
            if(x>=t-3000&&x<=t) {
                c++;
            }else{
                queue.poll();
            }
        }
        return c;
 
    }
}
 
/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter obj = new RecentCounter();
 * int param_1 = obj.ping(t);
 */
  • 在这里插入图片描述
 /**
     * 双指针法
     */
    public static int[] maxSlidingWindow1(int[] nums, int k) {
        //获取数组nums的长度
        int length = nums.length;
        //如果nums的长度小于0或者小于k,返回null
        if(length<=0||length<k){
            return new int[]{};
        }
        //新建滑动窗口数组结果集数组,数组长度应为length-k-1
        int[] res=new int[length-k+1];
        //新建第一个指针
        int first=0;
        //新建第二个指针
        int second=k-1;
        //双指针同时移动,直到second=length-1结束
        while(second<=length-1){
            int max=nums[first];
            for (int i = first+1; i < first+k; i++) {
                if(nums[i]>max){
                    max=nums[i];
                }
            }
            res[first]=max;
            first++;
            second++;
        }
        return res;
    }

  • 在这里插入图片描述
class KthNumber {
public:
    int findKth(int k) {
        // write code here
vector<int> res(k+1);
        int i=0,j=0,t=0;
        res[0]=1;
        int num=0;
        for(int h=1;h<=k;h++)//不能从0开始,不然res[0]=3;影响第二个数5的产生
            {
            num=min(res[i]*3,min(res[j]*5,res[t]*7));
            res[h]=num;
            if(num==res[i]*3) i++;
            if(num==res[j]*5) j++;
            if(num==res[t]*7) t++;
        }
        return res[k];
    }
};
  • 在这里插入图片描述
class MyStack {
	private LinkedList<Integer> queue1;
	private LinkedList<Integer> queue2;
    public MyStack() {
        queue1=new LinkedList<Integer>();
        queue2=new LinkedList<Integer>();
    }
    
    public void push(int x) {
        if(queue1.isEmpty()&&queue2.isEmpty()){
        	queue1.addLast(x);
        }else if(queue1.isEmpty()){
        	queue2.addLast(x);
        }else{
        	queue1.addLast(x);
        }
    }
    
    public int pop() {
        if(queue1.isEmpty()){
            int len=queue2.size();
        	for(int i=0;i<len-1;i++){
        		queue1.addLast(queue2.removeFirst());
        	}
        	return queue2.removeFirst();
        }else{
            int len=queue1.size();
        	for(int i=0;i<len-1;i++){
        		queue2.addLast(queue1.removeFirst());
        	}
        	return queue1.removeFirst();
        }
    }
    
    public int top() {
        if(queue1.isEmpty()){
        	return queue2.getLast();
        }else{
        	return queue1.getLast();
        }
    }
    
    public boolean empty() {
        return queue1.isEmpty()&&queue2.isEmpty();
    }
}
  • 在这里插入图片描述
public class MyQueue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    /**
     * Initialize your data structure here.
     */
    public MyQueue() {
        stack1 = new Stack();
        stack2 = new Stack();
    }
    /**
     * Push element x to the back of queue.
     */
    public void push(int x) {
        stack1.push(x);
    }
    /**
     * Removes the element from in front of queue and returns that element.
     */
    public int pop() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
    /**
     * Get the front element.
     */
    public int peek() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.peek();
    }
    /**
     * Returns whether the queue is empty.
     */
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }
}


  • 在这里插入图片描述
   public boolean isValid(String s) {
        Stack <Character> stack =new Stack<>();
        Map<Character,Character> map= new HashMap<>();
        map.put(')','(');
        map.put('}','{');
        map.put(']','[');
        char[] chars= s.toCharArray();
        for(char ch: chars){
                if(stack.isEmpty()){
                        stack.push(ch);
                }else if(stack.peek()==map.get(ch)){
                    stack.pop();
                }else{
                    stack.push(ch);
                }
        }
        return stack.isEmpty();
    }
  • 在这里插入图片描述
class Solution {
    public int evalRPN(String[] tokens) {
 
        Stack<Integer> stack = new Stack<>();
        
        for(String s:tokens){
            switch(s){
                case "+":
                    stack.push(stack.pop()+stack.pop());
                    break;
                case "-":
                    stack.push(-stack.pop()+stack.pop());
                    break;
                case "*":  
                    stack.push(stack.pop() * stack.pop());
                    break;
                case "/": 
                    int num = stack.pop();                
                    stack.push(stack.pop() / num);
                    break;
                default:     
                    stack.push(Integer.valueOf(s));     
                    break;
            }
        }
        return stack.pop();
    }
}
  • 在这里插入图片描述
public List<Integer> topKFrequent2(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }

        // 创建 nums.length + 1 个桶
        List<Integer>[] bucket = new List[nums.length + 1];
        // 遍历map,根据value值 出现的次数 放到对应的桶中
        for (Map.Entry<Integer, Integer> e : map.entrySet()) {

            Integer value = e.getValue();
            if (bucket[value] == null) {
                bucket[value] = new ArrayList<>();
            }

            bucket[value].add(e.getKey());
        }

        List<Integer> freList = new ArrayList<>();
        // 桶的编号表示出现次数,所以倒数桶
        for (int j = bucket.length - 1; j > -1 && freList.size() < k; j--) {

            if (bucket[j] != null)
                freList.addAll(bucket[j]);
        }
        return freList;
    }

  • 在这里插入图片描述

    public static void add(int n) {
        // 计数变量
        int count = 0;
        // 循环每个数
        for (int i = 2; i < n; i++) {
            boolean sign = true;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    sign = false;
                    break;
                }
            }
            if (sign) {
                count++;
            }

        }
        System.out.println(count);
    }

  • 在这里插入图片描述
bool isIn(int* a,int c,int b) 
{
    int i;
    for(i = 0; i < c; i++)
        if(a[i] == b)
            return true;
    
    return false;
}
 
int* powerfulIntegers(int x, int y, int bound, int* returnSize){
    int i, j, k;
    int *ret = malloc(sizeof(int)*bound);
    int buf;
    int c = 0;
    
    for(j = 0; pow(y,j) < bound && j < 21; j++) {
        for(i=0; pow(x,i) < bound && i < 21; i++){
            buf = pow(y,j)+pow(x,i);
            if(buf <= bound){
                if(!isIn(ret,c,buf))
                    ret[c++] = buf;
            }
        }
    }
    
    *returnSize =c;
    return ret;
    
}
  • 在这里插入图片描述
class Solution {
public:
	vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
		// 用unordered_set对nums1中的元素去重
		unordered_set<int> s1;
		for (auto e : nums1)
			s1.insert(e);
		// 用unordered_set对nums2中的元素去重
		unordered_set<int> s2;
		for (auto e : nums2)
			s2.insert(e);
		// 遍历s1,如果s1中某个元素在s2中出现过,即为交集
		vector<int> vRet;
		for (auto e : s1)
		{
			if (s2.find(e) != s2.end())
				vRet.push_back(e);
		}
		return vRet;
	}
};
  • 在这里插入图片描述
public class Solution {
    public static void main(String[] args) {
        System.out.println(searchIndex("yayah"));
        System.out.println(searchIndex("hyaya"));
    }
    public static int searchIndex(String s){
        for(int i=0;i<s.length();i++){
            //charAt(int index)  返回指定索引位置的char值
            char ch = s.charAt(i);
            //lastIndexOf()  返回在字符串中最右边出现的指定字符串的索引
            //indexOf() 返回某个指定字符串的值在字符串中首次出现的位置
            if(s.indexOf(ch)==s.lastIndexOf(ch)){  
                return i;
            }
        }
        return -1;
    }
}

  • 在这里插入图片描述
class Solution(object):
    def isAlienSorted(self, words, order):
        """
        :type words: List[str]
        :type order: str
        :rtype: bool
        """
        length = len(words)
        for i in range(length-1):
            a = words[i]
            b = words[i+1]
            minlen = min(len(a),len(b))
            for j in range(minlen):
                if order.index(a[j]) < order.index(b[j]):
                    break
                elif order.index(a[j]) > order.index(b[j]):
                    return False
                elif j == minlen - 1 and len(b) < len(a):
                    return False
        return True

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发热的嘤嘤怪(2003计科胜胜同学)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值