Java语言程序设计——学习笔记(辽宁大学,王青松主讲)

目录

一、Java基础

二、代码训练

2.1字符串

2.1.1 split()练习

2.1.2 字符串整形转换

2.1.3 判断是不是一个合法的邮箱

2.1.4 返回串sub在串s中首次出现的位置,如果不存在,则返回-1,不许使用函数

2.1.5 字符串相关函数使用测试

2.1.6 字符串之间的比较

2.1.7 输出100到999之间的所有水仙花数

2.2数组

2.2.1 冒泡排序

2.2.2求出数组的最大数

2.2.3二维数组的显示和交换

2.2.4输出二维数组的最大数

2.3面向对象

2.3.1 圆对象:求所有圆的半径平均值

2.3.2 函数输出北京欢迎你,测试static

2.3.3 传值调用和传址调用的对比学习

2.3.4 日期类:求明天是哪天,判断这个月有几天

2.3.5 天体类练习

2.3.6 学生类练习

2.3.7 static的测试学习

2.3.8作业:编写公有汽车类练习

2.3.9 链表创建插入删除

2.4继承

2.4.1 继承的理解

2.4.2 final的理解

2.4.3 栈的创建与使用

2.5接口

2.5.1 继承和接口的比较学习

2.6内部类加面向对象综合练习

2.6.1 坐标比较

2.6.2 同一接口实现不同的内容

2.7异常处理

2.7.1 hello world 异常处理程序

2.7.2 除数不能为0

2.7.3 除数不能为0的第二种写法

2.7.4 自定义除数不能为0异常

2.8集合

2.9文件操作

2.9.1 sample2023.txt中每行代表一个文件,可能有很多行,大家统计文件类型个数,并把统计得到的文件类型输出出来。(有错误)


一、Java基础

     学习以下代码即可,适合有编程基础的人,如果没有编程基础,建议系统学习下再打。

二、代码训练

2.1字符串

2.1.1 split()练习

//创建一个字符串,然后通过",",将字符串分割成字符串数组,并且将字符串数组中的元素每个都输出出来
public class Division {
    public static void main(String [] args){
        String str = new String("abc,deff,ghi,jds");
        String[] newstr = str.split(",");
        for(int i = 0; i < newstr.length; i++){
            System.out.println(newstr[i]);
        }
        String[] newstr2 = str.split(",", 2);
        for(int j = 0; j < newstr2.length; j++){
            System.out.println(newstr2[j]);
        }
    }
}

2.1.2 字符串整形转换

//将整形456转换为字符串,二进制字符串,"456"转整形,求int最大值,求int类型数据所占用byte
public class IntegerTest {
    public static void main(String[] args){
        String str = Integer.toString(456);
        String str2 = Integer.toBinaryString(456);
        int i = Integer.parseInt("456");
        int maxint = Integer.MAX_VALUE;
        int intsize = Integer.SIZE;
        System.out.println("'456'的十进制表示为:" + str);
        System.out.println("'456'的二进制表示为:" + str2);
        System.out.println("\"456\"转换为十进制是:" + i);
        System.out.println("int类型的最大取值为:" + maxint);
        System.out.println("int类型的二进制位数为" + intsize);
    }
}

2.1.3 判断是不是一个合法的邮箱

//判断是不是一个合法的邮箱
public class judge_e_mail {
    public static void main(String [] args){
        String regex = "\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
        String str1 = "aaa@";
        String str2 = "aaaaaaa";
        String str3 = "[email protected]";
        //matches用于判断字符串是否和正则表达式匹配
        if (str1.matches(regex)) {
            System.out.println(str1 + "是一个合法的E_mail地址");
        }
        if (str2.matches(regex)) {
            System.out.println(str2 + "是一个合法的E_mail地址");
        }
        if (str3.matches(regex)) {
            System.out.println(str3 + "是一个合法的E_mail地址");
        }
    }
}

2.1.4 返回串sub在串s中首次出现的位置,如果不存在,则返回-1,不许使用函数

public class String_homework {
    public static int indexOf(String s, String sub) {
        //返回串sub在串s中首次出现的位置,如果不存在,则返回-1
        for(int i = 0; i < s.length(); i++){
            //从s中截取和sub长度一样的字符串,和sub比较,子串相同即找到,不相等再比较下一个新的字符串,直到找到或找不到
            for(int j = 0; j < sub.length(); j++){
                if (s.charAt(i + j) != sub.charAt(j)){
                    break;
                }
                if (s.charAt(i + j) == sub.charAt(j) && j != sub.length() - 1){
                    continue;
                }
                if (s.charAt(i + j) == sub.charAt(j) && j == sub.length() - 1){
                    return i;
                }
            }}
        return -1;
    }
    public static void main(String [] args){
        String s = "This is a book.";
        System.out.println(indexOf(s, "is"));
    }
}

2.1.5 字符串相关函数使用测试

public class test1 {
    public static void main(String[] args){
        //String用于创建不可改变字符串
        String s = "This is a book.";
        int iii = s.indexOf("this", 5);
        //去字符串空格
        String s_trim = s.trim();
        //取出某个字符
        char c = s.charAt(2);
        System.out.println("c: " + c);
        int i = s.length();
        //取子串
        String sub_s = s.substring(1);
        //引用
        String s1 = s.toUpperCase();
        String s2;
        s2 = s.replace("!", ".");
        System.out.println("sub_s = " + sub_s);
        System.out.println("s1 = " + s1);
        System.out.println("s2 =" + s2);
        System.out.println("s = " + s);
        // StringBuffer用于创建可改变的字符
        StringBuffer ss = new StringBuffer("drink java!");
        ss.insert(6, "Hot ");
        System.out.println("ss = " + ss);
        ss.setCharAt(0, 'D');
        System.out.println("ss = " + ss);
        String s_int = "1234";
        //使用了包装类integer,i=(int)s_int
        i = Integer.parseInt(s_int);
        System.out.println(i);
    }
}

2.1.6 字符串之间的比较


public class TestEqual {
    public static void main(String[] args){
        //字符串比较的集中对比
        String s1 = new String("abc");
        String s2 = new String("ABC");
        String s3 = new String("abc");
        //int address1 = System.identityHashCode(s1);
        //System.out.println(address1);
        boolean b2 = s1.equalsIgnoreCase(s2);
        boolean b = s1.equals(s2);
        System.out.println(s1 + " equal " + s2 + " :" + b);
        System.out.println(s1 + " equalsIgnoreCase " + s2 + " :" + b2);
        b = (s1 == s3);
        /*s1 == s3 false原因是两个等号判断的是字符串的地址是否相等,字符串关于值的
        判断要用equals*/
        System.out.println("s1 == s3 " + b);
        String s4 = "abc";
        String s5 = "abc";
        String s6 = "abcd";
        b = (s4 == s5);
        System.out.println("s4 == s5 " + b);
        b = (s5 == s6);
        System.out.println("s5 == s6 " + b);
        s6 = "abc";
        b = (s5 == s6);
        System.out.println("*********************s5==s6 " + b);
        String  str = "abcd";
        System.out.println(str.compareTo("cat"));
    }
}

2.1.7 输出100到999之间的所有水仙花数

public class Water_flower {
    static boolean sxh(int n){
	   /*n是三位整数,判断n是否为水仙花数,如果是返回true,否则返回false
	     水仙花数等于其个位数的立方加十位数的立方加百位数的立方。
	     例如,153=1的立方+5的立方+3的立方,所以153是水仙花数 */
        String n_str =Integer.toString(n);
        int sum = 0;
        int j = 0;
        for(int i = 0; i < 3; i++){
            //将j转换成整形
            j = n_str.charAt(i) - '0';
            sum += j * j * j;
        }
        if (sum == n){
            return true;
        }
        return false;
    }
    static void printsxh(){
        //输出100到999之间的所有水仙花数
        for(int i = 100; i < 1000; i++){
            if(sxh(i)){
                System.out.print(i + ",");
            }
        }
    }
    public static void main(String[] args) {
        System.out.println("100到999之间的所有水仙花数:");
        printsxh();  //调用方法输出100-999的水仙花数
    }
}

2.2数组

2.2.1 冒泡排序

public class BubbleSort {
    public static void main(String[] args) {
        // 创建一个数组,这个数组元素是乱序的
        int[] array = { 63, 4, 24, 1, 3, 15 };
        // 创建冒泡排序类的对象
        BubbleSort sorter = new BubbleSort();
        // 调用排序方法将数组排序
        sorter.sort(array);
    }

    /**
     *冒泡排序
     *
     * @param array
     *            要排序的数组
     */
    public void sort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            // 比较相邻两个元素,较大的数往后冒泡
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];// 把第一个元素值保持到临时变量中
                    array[j] = array[j + 1];// 把第二个元素值保存到第一个元素单元中
                    array[j + 1] = temp;// 把临时变量也就是第一个元素原值保持到第二个元素中
                }
            }
        }
        showArray(array);// 输出冒泡排序后的数组元素
    }

    /**
     * 显示数组所有元素
     *
     * @param array
     *            要显示的数组
     */
    public void showArray(int[] array) {
        for (int i : array) {// foreach格式遍历数组
            System.out.print(" >" + i);// 输出每个数组元素值
        }
        System.out.println();
    }
}

2.2.2求出数组的最大数

import java.util.*;
public class Array_Max{
    public static void main(String[] args)  {
        //求N个数的最大数
        final int N=5;
        int score[]=new int[N];
        int max;

        Scanner reader=new Scanner(System.in);
        System.out.println("Input "+N+" number ,Please:");
        for(int i=0;i<N;i++)
            score[i]=reader.nextInt();
        max=score[0];
        for(int i=1;i<score.length;i++)
            if(score[i]>max) max=score[i];
        System.out.println("max="+max);
    }
}

2.2.3二维数组的显示和交换

public class arr_2 { // 创建类
    public static void change(int[][] a){
        //将数组本身的数据行列互换
        int i,j,temp;
        for(i=1;i<a.length;i++) //对矩阵a的下三角循环
            for(j=0;j<i;j++){//将a[i][j]和a[j][i]交换
                temp=a[i][j];
                a[i][j]=a[j][i];
                a[j][i]=temp;
            }
    }
    public static void showArray(int[][] arr){
        //将数组的数据按行显示
        for(int i = 0;i<arr.length;i++){
            for(int j=0;j<arr[i].length;j++){
                System.out.print(arr[i][j]+"\t");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        int arr[][]=new int[][]{
   
   {1,2,3},{4,5,6},{7,8,9}};
        System.out.println("数组原有内容:");
        showArray(arr);
        change(arr);//将数组arr的数据行列互换
        System.out.println("行列互换后数组内容:");
        showArray(arr);
    }
}

2.2.4输出二维数组的最大数

import java.util.*;
public class TwoArray_Max{
    public static void main(String[] args)  {
        /*通过键盘给3*4的二维数组输入数据,
         *然后按行输出数组元素,
         *并输出数组中最大的元素及行和列号
         **/
        final int N=3,M=4;
        int a[][]=new int[N][M];
        Scanner reader=new Scanner(System.in);
        System.out.println("Input "+N+"*"+M+" number ,Please:");
        for(int i=0;i<a.length;i++)
            for(int j=0;j<a[i].length;j++)
                a[i][j]=reader.nextInt();
        System.out.println("数组中元素是");
        int max,row,col;
        max=a[0][0];
        row=col=0;
        for(int i=0;i<a.length;i++){
            for(int j=0;j<a[i].length;j++){
                System.out.printf("%5d",a[i][j]);
                if(a[i][j]>max){max=a[i][j];row=i;col=j;}
            }
            System.out.println();
        }
        System.out.println("row="+row+"  col="+col+"  max="+max);
    }
}

2.3面向对象

2.3.1 圆对象:求所有圆的半径平均值

运行指南:这两个文件都放在Object_oriented1包下,然后运行Circle_test。

//file_name:Circle
package Object_oriented1;
public class Circle {
    private static double PI=3.14;
    private double radius;
    public Circle(double r) {
        radius=r;
    }
    public static double average(Circle c[]) {
        //用来返回Circle对象数组里所有radius成员的平均值。
        double sum=0.0;
        for(int i=0;i<c.length;i++)
            sum+=c[i].radius;
        return (sum/c.length);
    }
}

//flie_name:Circle_test
package Object_oriented1;
public class Circle_test {
    public static void main(String args[])
    {
        Circle cir[]=new Circle[3];
        cir[0]=new  Circle(1.0);
        cir[1]=new  Circle(4.0);
        cir[2]=new  Circle(2.0);
        System.out.println("radius??????????  "+Circle.average(cir));
        //System.out.println("???PI????  "+Circle.?);PI是private搞不出来,改成public才可以输出
    }
}

2.3.2 函数输出北京欢迎你,测试static

package Object_oriented1;
public class Chinese {
    public static void main(String [] args){
        sing();
    }
    static{
        System.out.println("hello");
    }
    static void sing(){
        System.out.println("北京欢迎你");
    }
}

2.3.3 传值调用和传址调用的对比学习

1) 如下,传值调用不会改变变量的值,在函数弹栈后,原变量的值不变。

//flie_name:value_test
public class value_test {
    public static void main(String [] args){
        int b = 10;
        System.out.println("传值调用传值调用HalfInt之前b="+b);
        halfint(b);
        System.out.println("传值调用HalfInt之后b="+b);
    }
    public static void halfint(int a){
        a /= 2;
    }
}

2) 如下,传址调用会改变变量的值,在函数弹栈后,原变量的值改变。

//file_name:adress_test
class Person{
    String name;
    int age;
    String sex;
    public Person(String _name, int _age, String _sex){
        name = _name;
        age = _age;
        sex = _sex;

    }
}
public class adress_test {
    public static void main(String [] args){
        Person a = new Person("zhangsan", 20, "男");
        System.out.println("传址调用changeAge之前age="+a.age);
        changeAge(a);
        System.out.println("传引用调用changeAge之后age="+a.age);
    }
    public static void changeAge(Person p){
        p.age = 18;
    }
}

2.3.4 日期类:求明天是哪天,判断这个月有几天

package Object_oriented1;
public class Date{
    private int day,month,year;
    Date(int i,int j,int k){
        day = i;    month = j;     year = k;
    }
    Date(){
        day = 1;    month = 1;   year = 1998;
    }
    Date(Date d){
        day=d.day; month = d.month; year = d.year;
    }
    public void printDate(){
        System.out.print(day+"/"+month+"/"+year);
    }
    public Date tomorrow(){
        Date d = new Date(this);
        d.day++;
        if(d.day>d.daysInMonth()){
            d.day = 1;       d.month++;
            if(d.month > 12){
                d.month = 1;  d.year ++;
            }
        }
        return d;
    }
    public int daysInMonth(){
        switch(month){
            case 1:case 3:case 5: case 7:
            case 8:case 10:case 12:
                return 31;
            case 4:case 6:case 9:case 11:
                return 30;
            default:
                if((year%400==0)||(year % 100 !=0 && year % 4 ==0))
                    return 29;
                else return 28;
        }
    }
    public static void main(String args[]){
        Date d1 = new Date();
        System.out.print("The current date is(dd/mm/yy):");
        d1.printDate();
        System.out.println();
        System.out.print("Its tomorrow is(dd/mm/yy):");
        d1.tomorrow().tomorrow().printDate();
        System.out.println();
        Date d2 = new Date(28,2,1964);
        System.out.print("The current date is(dd/mm/yy):");
        d2.printDate();
        System.out.println();
        System.out.print("Its tomorrow is(dd/mm/yy):");
        d2.tomorrow().printDate();
        System.out.println();
    }
}

2.3.5 天体类练习

//天体类
public class Body {
    public long idNUM;//唯一标识天体
    public String nameFor= "unnamed";//天体名字
    public Body oribits = null;//环绕天体
    public static long nextID = 0;//下一个天体号
    Body(){
        idNUM = nextID++;
    }
    Body(String bodyNAME, Body oribitsAround){
        this();
        nameFor = bodyNAME;
        oribits = oribitsAround;
    }
    public static void main(String [] args){
        Body sun = new Body("Sun", null);
        Body earth = new Body("Earth", sun);
        Body xxx = new Body();
        System.out.println(xxx.idNUM + " " + xxx.nameFor);
        System.out.println(earth.oribits.nameFor);
        System.out.println(Body.nextID);
    }
}

2.3.6 学生类练习

package oo1;
class Student                       //类名是Student
  {
	 String name;                   //类的属性也叫,类的成员
     int birth;
     Student(){}
     Student(String _name,int _birth)          //构造器
      {
         name = _name;                  //给属性赋值
         birth = _birth;
      }
    public void show()             
                          //公用方法名称为show,没有返回值
      {
        System.out.println("姓名="+name);    //输出姓名
        System.out.println("生日="+birth);
      }
     
  }//Student                       
public class Student_Test {
	public static void main(String[] args) {
		 // Student d3= new Student();
		   Student d1= new Student("张三",19510101);  //d1对象实体
	       Student d2= new Student("李四",19680808);
	       System.out.println("对象d1的属性及方法");
	       System.out.println("name="+d1.name);   //d1对象属性name
	       System.out.println("birth="+d1.birth);
	       d1.show();     //d1对象show方法
	       d1.name="张三丰";
	       System.out.println("对象d2的属性及方法");
	       System.out.println("name="+d2.name);
	       System.out.println("birth="+d2.birth);
	       d2.show();
	}
}

2.3.7 static的测试学习

1)静态属性(类属性)学习

public class static_test{
    static  int  count=0;   //静态属性,也叫类属性,各对象共享此属性
    String   xh;      //学号
    String   name;    //姓名
    static_test(String  xh1,String name1){
        xh=xh1;
        name=name1;
        count++;
    }
    public  void show(){
        System.out.println("xh="+xh+"  name="+name);
    }
    public  static void showcount(){//静态方法,也叫类方法
        System.out.println("学生数是:"+count);
    }
    public static void main(String args[]){
        static_test  s1=new static_test("1","张三");
        static_test  s2=new static_test("2","李四");
        s1.show();
        s2.show();
        System.out.println("学生数是:"+static_test.count);
        static_test.showcount();
        System.out.println(s1.name);
        System.out.println(s2.name);
        System.out.println(s1.count);
        System.out.println(s2.count);
        s1.showcount();
        s2.showcount();
    }
}

2) 静态块,代码块,构造器测试学习

public class StaticTest2 {// 初始化顺序
    static int a = 1;
    {
        a = 2;
        System.out.println("代码块"+ a);
    }
    // 仅执行一次
    static {
        a = 3;
        System.out.println("静态块"+a);
    }
    public StaticTest2() {//构造器

        a = 4;
        System.out.println("构造方法" + a);
    }
    public static void main(String[] args) {
        StaticTest2 s=new StaticTest2();
        //System.out.println(new StaticTest2().a);
        System.out.println(s.a);
        System.out.println(new StaticTest2().a);
    }
}

2.3.8作业:编写公有汽车类练习

/*
2023.3.30练习:
编写一个公有Car类,包含这样两个属性:当前速度 speed (整型)及车主的姓名name (字符串型)包含一个show0方法可用来显
示两个属性的值,包含一个构造器可以初始化两个属性,在main方法中定义两个Car类型的对象c,d并调用各自的方法。
 */
public class car {
    public int speed;
    public String name;
    car(int _speed, String _name){
        speed = _speed;
        name = _name;
    }
    public void show(){
        System.out.println("速度" + speed);
        System.out.println("名字" + name);
    }
    public static void main(String [] args){
        car c = new car(134, "freezing");
        car d = new car(324,"rebecca");
        c.show();
        d.show();
    }
}

2.3.9 链表创建插入删除

import java.util.Scanner;
public class SingleLinkList {
    //Node的定义在Node里面,下面的代码
    Node head=null;  //链表的头指针
    public void createList(int n) {
        //创建含n个结点的带头结点的单链表(尾插法)
        if(n<1) return;
        head = new Node();//生成头结点
        Node r,p;
        int data;
        r=head;  //r在链表尾部
        System.out.println("输入"+n+"个整数,用来创建单链表");
        Scanner reader=new Scanner(System.in);
        for(int i=1;i<=n;i++) {
            data=reader.nextInt(); //由键盘输入一个整数
            p=new Node(data); //申请一个结点
            r.next=p; //将新来结点链接在r的后面
            r=p; //r指向p
        }
        reader.close();
    }
    public void printList() {
        Node p;
        System.out.print("The List:");
        p=head.next; //p指向链表的第一个结点
        while(p!=null) {
            System.out.print(p.data+"\t");
            p=p.next;
        }
        System.out.println(); //换行
    }
    public int length() {
        //返回单链表的长度,不包括头结点
        Node p;
        p=head.next;
        int count=0;
        while(p!=null) {
            count++;
            p=p.next;
        }
        return count;
    }
    public boolean insertList(int i,int e) {
        //在链表的第i个结点前插入一个值为e的结点,插入成功返回true,否则返回false
        Node p=head;
        int j=0;
        if(i<1) return false;
        while(p!=null&&j<i-1) {
            j++;
            p=p.next;
        }
        if(p==null) return false;
        Node q=new Node(e);
        q.next=p.next;
        p.next=q;
        return true;
    }
    public boolean deleteList(int i) {
        //删除链表的第i个结点,删除成功返回true,否则返回false
        Node p=head;
        int j=0;
        if(i<1) return false;
        while(p!=null&&j<i-1) {
            j++;
            p=p.next;
        }
        if(p==null||p.next==null) return false;
        p.next=p.next.next;
        return true;
    }
    public static void main(String[] args) {
        SingleLinkList L=new SingleLinkList();
        L.createList(5);
        L.printList();
        System.out.println("length="+L.length());
        if(L.insertList(2, 99)) {
            System.out.println("insert success!");
            L.printList();
        }
        L.deleteList(2);
        L.printList();

    }

}
public class Node { //结点的定义
    int data; //数据域
    Node next; //引用,下一个结点
    public Node() {
        next=null;
    }
    public Node(int data) {
        this();
        this.data=data;
    }
}

2.4继承

2.4.1 继承的理解

class A{
    void call(){
        System.out.println("A's call() method");
    }
}
class B extends A{
    void call(){
        System.out.println("B's call() method");
    }
    void other(){
        System.out.println("B......");
    }
}
public class Dispatch{
    public static void main(String args[]){
        A a= new B();
        A c = new A();
        //也叫对象转换,反过来不可以,如(B a= new A())
        a.call(); //可以调用a.other吗?
        System.out.println("---------------------------------");
        B b=new B();
        ((A)b).call();
    }
} //Dispatch

2.4.2 final的理解

package Object_oriented2;
// 终结类:不能被继承
public final class FinalTest {

    // 常量:只能通过显示初始化或构造器初始化
    public final int x = 1;

    // 终结方法:不能被 重写
    public final void method() {
        // 局部常量
        final int y = 2;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FinalTest a = new FinalTest();
        System.out.println(a.x);
        //a.x = 2;
        a.method();
        System.out.println(a.x);
    }

}

2.4.3 栈的创建与使用

以下两个文件在同一个包下

package Object_oriented2;
public class MyStack {
    private int[] data;
    private int top = -1;
    private int size;  //最大容量

    public MyStack() {
        data = new int[100];
        this.size = 100;
    }

    public MyStack(int size) {
        data = new int[size];
        this.size = size;
    }

    public void push(int obj) {
        if (top < size - 1) {
            top++;

            this.data[top] = obj;
        }
        else System.out.println("栈满!");
    }

    public int pop() {
        int t;

        if (top > -1) {
            t = this.data[top];
            top--;
            return  t;
        }
        System.out.println("栈空!");
        return -9999;
    }

    public void printAll() {
        for (int i = 0; i <= top; i++) {
            System.out.println(data[i]);
        }
    }

}

package Object_oriented2;
public class MyStackTest {
    public static void main(String[] args) {
        int t;
        MyStack stack = new MyStack();

        // 入栈
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);

        stack.printAll();

        // 出栈
        t=stack.pop();
        if(t!=-9999)  System.out.println("弹出的栈顶元素为:"+t);
        t=stack.pop();
        if(t!=-9999)  System.out.println("弹出的栈顶元素为:"+t);
        stack.printAll();
        stack.pop();
        stack.pop();
        stack.pop();
    }
}

2.5接口

2.5.1 继承和接口的比较学习

接口的声明:接口中只包含常量和抽象方法,而没有变量和方法的实现(如:shape)

package Object_oriented2;
//
//public class Shape {
//    double girth;//周长
//    double area;//面积
//    public double getGirth(){
//        return girth;
//    }
//    public double getArea(){
//        return area;
//    }
//}
interface Shape {
    public double getGirth();
    public double getArea();
}

矩形:shape接口

package Object_oriented2;

public class Rect implements Shape{
    //矩形
    double width;
    double height;
    public Rect(double width, double height){
        this.width = width;
        this.height = height;
    }
    public Rect(){}
    public double getGirth(){
        //方法覆盖overload,求矩形周长
        return (width + height) * 2;
    }
    public  double getArea(){
        return width * height;
    }
}

正方形:继承矩形

package Object_oriented2;

public class Square extends Rect{
    public  Square(double width){
        super(width, width);
    }
}

圆形:shape接口

package Object_oriented2;

public class Circle implements Shape{
    double r;
    final double PI = 3.1415;
    public Circle(double r){
        this.r = r;
    }
    public Circle(){};
    public double getGirth(){
        return 2 * PI * r;
    }
    public double getArea(){
        return PI * r * r;
    }

}

2.6内部类加面向对象综合练习

2.6.1 坐标比较

import java.util.Arrays;
import java.util.Comparator;
public class Array_sort {
    Point[] arr;
    Array_sort(){
        arr = new Point[4];
        for(int i = 0; i < arr.length; i++)
            arr[i] = new Point();
    }
    public static void main(String [] args){
        //初始化对象中的数据
        Array_sort sort = new Array_sort();
        sort.arr[0].x = 2; sort.arr[0].y = 1;
        sort.arr[1].x = 2; sort.arr[1].y = 2;
        sort.arr[2].x = 1; sort.arr[2].y = 2;
        sort.arr[3].x = 0; sort.arr[3].y = 2;
        Arrays.sort(sort.arr, new MyComprator());    //使用指定的排序器,进行排序
        for(int i=0;i<4;i++)    //输出排序结果
            System.out.println("("+sort.arr[i].x+","+sort.arr[i].y+")");
    }
}
class Point{
    int x;
    int y;
}
//比较器
class MyComprator implements Comparator{
    public int compare(Object arg0, Object arg1) {
        Point t1=(Point)arg0;
        Point t2=(Point)arg1;
        if(t1.x != t2.x)
            return t1.x>t2.x? 1:-1;
        else
            return t1.y>t2.y? 1:-1;
    }
}

2.6.2 同一接口实现不同的内容

package Object_oriented1;
interface CallBack{
    //执行回调操作的方法
    void execute(); //统一的接口实现不同的内容
}
public class tools {
    public static void main(String [] args){
        tools tool = new tools();
        System.out.println("String");
        tool.testTime(new CallBack() {
            @Override
            public void execute() {//测试String性能
                String str = new String();
                for(int i = 0; i < 10000; i++)
                    str = str + i;
            }
        });
        System.out.println("StringBuffer ");
        tool.testTime(new CallBack() {
            @Override
            public void execute() {//测试StringBuffer性能
                StringBuffer sbf = new StringBuffer();
                for(int i = 0; i < 100000; i++)
                    sbf.append(i);
            }
        });
        System.out.println("StringBuffer ");


    }
    public void testTime(CallBack callback){
        long begin = System.currentTimeMillis();//测试起始时间
        callback.execute();
        long end = System.currentTimeMillis();//测试结束时间
        System.out.println("[use time] : " + (end - begin));
    }
}

2.7异常处理

2.7.1 hello world 异常处理程序

package exception;

public class HellowWorldEx {
    public static void main(String[] args){
        int i = 0;
        String[] greetings = {"hellow", "ok", "hi"};
        while(i < 4){
            try{
                System.out.println();
                System.out.println(greetings[i]);
            }
            catch(ArrayIndexOutOfBoundsException e){
                System.out.println("re_setting index value");
                break;
            }
            catch(Exception e){
                System.out.println(e.toString());
                e.printStackTrace();
                break;
            }
            finally {
                System.out.println("This is always printed");
            }
            i++;
        }
        System.out.println("programm ...");

    }
}

2.7.2 除数不能为0

package exception;
import java.util.Scanner;

public class QuotientWithMethod {
    public static int quotient(int n1, int n2){
        if (n2 == 0){
            throw new ArithmeticException("Divisor cannot be zero");
        }
        return n1/n2;
    }
    public static void main(String[] args){
        Scanner r = new Scanner((System.in));
        System.out.println("Enter two Integers:");
        int n1 = r.nextInt();
        int n2 = r.nextInt();
        r.close();
        try {
            int result = quotient(n1, n2);
            System.out.println(n1 + " / " + n2 + " is " + result);
        }
        catch(ArithmeticException e){
            System.out.println("Execution an integer " + e.getMessage());
        }
        System.out.println("Execution continues...");
    }
}

2.7.3 除数不能为0的第二种写法

package exception;
import java.util.Scanner;
public class QuotientWithMethod_1 {
    public static int quotient(int n1,int n2) {
        if(n2==0) {
            System.out.println("Divisor cannot be zero");
            System.exit(1);
        }
        return n1/n2;
    }
    public static void main(String[] args) {
        Scanner r=new Scanner(System.in);
        System.out.println("Enter two Integers:");
        int n1=r.nextInt();
        int n2=r.nextInt();
        r.close();
        int result=quotient(n1,n2);
        System.out.println(n1+" / "+n2+" is "+result);
        System.out.println("Execution continues...");
    }
}

2.7.4 自定义除数不能为0异常

package exception;
import java.util.InputMismatchException;
import java.util.Scanner;
class MyException extends Exception{//创建自己的异常类,必须继承Exception
    private String message;
    public MyException(String ErrorMessage){
        message = ErrorMessage;
    }
    public String getMessage(){
        return message;
    }

}

public class ExceptionDemo {
    static int quotient(int x, int y) throws MyException{//自定义方法抛出异常
        if (y < 0)
            throw  new MyException("除数不能是负数");
        else if (y == 0)
            throw new MyException("除数不能是0");
        return x/y;
    }
    public static void main(String [] args){
        int m, n;
        System.out.println("输入两个数m,n:");
        Scanner r = new Scanner(System.in);
        try{
            m = r.nextInt();
            n = r.nextInt();
            int result  = quotient(m, n);
            System.out.println(m + " / " + n + " = " + result);
        } catch(InputMismatchException e){
            System.out.println("输入数据不合理!");
        }
        catch (MyException e){//处理自定义异常
            System.out.println(e.getMessage());
        }
        catch (Exception e){
            System.out.println("程序发生了其他异常");
        }
        finally {
            r.close();
        }

    }
}

2.8集合

2.9文件操作

2.9.1 sample2023.txt中每行代表一个文件,可能有很多行,大家统计文件类型个数,并把统计得到的文件类型输出出来。(有错误)

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;

public class file_homework {
    public static void main(String [] args) throws IOException {
        FileReader file = new FileReader("sample2023.txt");
        // 使用ArrayList来存储每行读取到的字符串
        ArrayList<String> arrayList = new ArrayList<String>();
        BufferedReader bf = new BufferedReader(file);
        HashMap<String,Integer> result = new HashMap<>();
        String str;
        while ((str = bf.readLine()) != null) {
            arrayList.add(str);
        }
        bf.close();
        file.close();
        for(int i = 0; i < arrayList.toArray().length; i++){
            String str_2 = arrayList.get(i);
            char[] str_arr = str_2.toCharArray();
            for(int j = 0; j < str_arr.length; j++){
                if(arrayList.get(i).toCharArray()[j] == '.'){
                    String file_type_string = str_2.substring(j + 1, str_arr.length);
                    if(result.containsKey(file_type_string)){
                        //出现过,先得到集合中的出现次数再自加
                        Integer count = result.get(file_type_string);
                        count++;
                        result.put(file_type_string, count);
                    }else {
                        //没出现直接放进集合中
                        result.put(file_type_string, 1);
                    }
                }

            }
        }
    System.out.println(result);
    }
}

sample2023.txt

2018/10/12  17:11           189,137    20181005-01_页面_1.jpg
2018/10/10  16:19           137,564 20181005-01.pdf
2018/10/12  17:11           189,124    20181005-01_页面_2.jpg
2013/04/23  09:25           1,940,285  00-12.pdf
2018/10/12  15:49            12,022 wwww.docx

2.10 GUI编程

2.11 多线程技术

2.12 网络编程

猜你喜欢

转载自blog.csdn.net/weixin_45440484/article/details/130648834