zoukankan      html  css  js  c++  java
  • Java入门学习笔记(全)

    JAVA

    https://zhuanlan.zhihu.com/p/21454718
    引用部分实验楼代码,侵删
    先通读文档 再亲自试标程 复习时自己再批注

    1.a = b += c = -~d a = (b += (c = -(~d)))
    2.如果 + 号的操作数中有一个
    是字符串,另一个也会转换成字符串。如果想把加法和连接放在一起使用,一定要使用
    括号。例如:
    System.out.println("Total: " + 3 + 4); // 打印“Total: 34”,不是7!
    3.虽然求模运算符的操作数一般是整数,但也可以使用浮点数。例如,4.3%2.1
    的结果是 0.1。
    4.System.out.println("7/3.0 is"+(double)7/3);
    5.如果使用 == 比较两个数字或字符,而且两个操作数的类型不同,在比较之前会把取值范围窄的操作数转换成取值范围宽的操作数类型。例如,比较 short 类型的值和 float
    类型的值时,在比较之前会先把 short 类型的值转换成 float 类型。
    6.int b=12;
    System.out.println(~b);
    按位取反
    7.>>带符号右移>>>不带符号右移
    -50 >> 2 // 11001110 >> 2 = 11110011 = -13 != -50/4
    -50 >>> 2 // 0xFFFFFFCE >>> 2 = 0x3FFFFFF3 1073741811
    8.

    // true:所有字符串都是String类的实例
    "string" instanceof String
    // true:字符串也是Object类的实例
    "" instanceof Object
    // false:null不是任何类的实例
    null instanceof String
    Object o = new int[] {1,2,3};
    o instanceof int[] // true:这个数组是int数组
    o instanceof byte[] // false:这个数组不是byte数组
    o instanceof Object // true:所有数组都是Object类的实例
    // 使用instanceof确保能放心校正对象
    if (object instanceof Point) {
     Point p = (Point) object;
    }
    
    switch 语句可以使用多个 case 子句标注同一个希望执行的语句。例如下面这个方法中的
    switch 语句:
    boolean parseYesOrNoResponse(char response) {
     switch(response) {
     case 'y':
     case 'Y': return true;
     case 'n':
     case 'N': return false;
     default:
     throw new IllegalArgumentException("Response must be Y or N");
     }
    }
    
    // 这些是我们想打印的数字
    int[] primes = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
    // 这是打印这些数字的循环
    for(int n : primes)
     System.out.println(n);
    

    11.synchronized排他锁//多线程
    synchronized ( expression ) {
    statements
    }
    expression 表达式的计算结果必须是一个对象或数组。statements 是能导致破坏的代码
    块,必须放在花括号里。
    执行语句块之前,Java 解释器先为 expression 计算得到的对象或数组获取一个排它锁
    (exclusive lock),直到语句块执行完毕后再释放。只要某个线程拥有对象的排它锁,其他
    线程就不能再获取这个锁。

    public class HelloWorld {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		System.out.println("Hello!Fucking World!");
    		int sum=1;
    		double ans=(1.0*sum)/Math.sqrt(1.234*4);
    		System.out.println(ans);
    		System.out.println("1234"+5+6);
    		System.out.println(4.3%2.1);
    		System.out.println("7/3.0 is"+(double)7/3);
    		
    		int []primes= {1,2,3,4,5,6,7,8,9};
    		for(int n:primes)
    		{
    			System.out.print();
    			
    		}
    	}
    	
    
    }
    
    

    常量

    final double pi = 3.14 常量
    常量也可以先声明再进行赋值,但是只能赋值一次,与C++有所不同
    String是一个常量,它的值在创建后不能修改
    equals()来判断两个字符串是否相同,是用的(O(mn))的方法
    而使用"=="比较的是两个对象在内存中存储的地址是否一样。
    而且使用 进行连接,不仅可以连接字符串,也可以连接其他类型。但是要求进行连接时至少一个元素是字符串

    
    public class HelloWorld {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		String s1="java";
    		String s2=new String("Java");
    		System.out.println(s1.equals(s2));//false
    		System.out.println(s1.equalsIgnoreCase(s2));//true无视大小写
    		boolean b=(s1==s2);
    		System.out.println(b);
    		String s3=s1+s2;
    		String s4=s1.concat(s2);
    		System.out.println(s3);
    		System.out.println(s4);
    		System.out.println();
    		int len=s1.length();
    		for(int i=0;i<len;i++)
    		{
    			System.out.println(s1.charAt(i));//相当于C++的取分量
    		}
    
    		
    	}
    	
    
    }
    
    

    indexOf(ch) 搜索字符ch第一次出现的索引
    indexOf(String)搜索子串第一次出现的索引
    lastIndexOf()最后一次出现

    public class StringTest {
        public static void main(String[] args) {
             String s = "abcdefabc";
             System.out.println("字符a第一次出现的位置为"+s.indexOf('a'));
             System.out.println("字符串bc第一次出现的位置为"+s.indexOf("bc"));
             System.out.println("字符a最后一次出现的位置为"+s.lastIndexOf('a'));
             System.out.println("从位置3开始到结束的字符串"+s.substring(3));
             System.out.println("从位置3开始到6之间的字符串"+s.substring(3,6));
        }
    }
    字符a第一次出现的位置为0
    字符串bc第一次出现的位置为1
    字符a最后一次出现的位置为6
    从位置3开始到结束的字符串defabc
    从位置3开始到6之间的字符串def
    
    

    使用scanner类去除字符串空格

    
    import java.util.Scanner;
    public class HelloWorld {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		String s=sc.nextLine();
    		int len=s.length();
    		String ans="";
    		for(int i=0;i<len;i++)
    		{
    			if(s.charAt(i)!=' ')
    			{
    				ans=ans+s.charAt(i);
    			}
    		}
    		System.out.println(ans);	
    	}
    	
    
    }
    
    
    import java.util.Scanner;
    
    public class HelloWorld {
    	public static void func()
    	{
    		System.out.println("wait!I will rape your mother.");
    	}
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		
    		func();
    		
    	}
    }
    
    
    
    switch(表达式){
        case 值1:
            代码块1
            break;
        case 值2:
            代码块2
            break;
        ...
        default:
            默认执行的代码块
    }
    
    

    int [] ages = {12,18,9,33,45,60}; //声明并初始化了一个整型数组,它有6个元素
    char [] symbol = new char[10] //声明并分配了一个长度为10的char型数组

    和C++不同,它的方括号是放在前面的

    int [] a1 = {1,2,3};
    int [] a2;
    a2 = a1;
    

    这里的a2是a1的一个引用

    int []a= {1,2,3,4,5,6};
    		for(int num:a)
    		{
    			System.out.println(num);
    		}//这样可以auto遍历数组
    这样一直输入
    Scanner in=new Scanner(System.in);
    		String temp;
    		//temp=in.nextLine();
    		while(true)
    		{
    			temp=in.nextLine();
    			System.out.println(temp);
    			if(temp.equals("end"))
    			{
    				break;
    			}
    		}
    		
    

    面向对象

    1.==会判断两个对象的地址是否相同,无需重载
    2.final 修饰类,则该类不允许被继承,为最终类
    final 修饰方法,则该方法不允许被覆盖(重写)
    final 修饰属性:则该类的属性不会进行隐式的初始化(类的初始化属性必须有值)或在构造方法中赋值(但只能选其一)
    final 修饰变量,则该变量的值只能赋一次值,即常量
    3. private 只有本类可以访问
    ​ 默认都可以访问
    protected子类也可以访问
    public万物皆可访问
    继承 class 子类 extends 父类
    java只有单继承和public继承
    java没有->运算符,都用点来代替super用于访问父类对象

    方法重载有以下几种规则:
    
    方法中的参数列表必须不同。比如:参数个数不同或者参数类型不同。
    访问权限,返回值类型和抛出的异常不同不能实现重载
    重载的方法中允许抛出不同的异常
    可以有不同的返回值类型,但是参数列表必须不同
    可以有不同的访问修饰符
    

    ​ 注意允许不同的异常,所以异常不同不能重载

    public class Test{
        public static void main(String args[]){
               Animal a = new Animal(); // Animal 对象
            Dog d = new Dog();   // Dog 对象
    
              Animal b = new Dog(); // Dog 对象,向上转型为Animal类型,具体会在后面的内容进行详解
    
              a.bark();// 执行 Animal 类的方法
             d.bark();//执行 Dog 类的方法
              b.bark();//执行 Dog 类的方法
           }
    }
    
    

    向上转换时(父类引用指向子类对象时,子类中的同名函数覆盖父类中的)

    不能用一个子类引用指向父类引用

    java实现多态有三个必要条件:继承·重写和向上转型

    abstract 抽象

    public class CellPhone extends TelePhone {
    
        @Override
        public void call() {
            System.out.println("我可以打电话!");
        }
    
        @Override
        public void message() {
            System.out.println("我可以发短信!");
        }
    
        public static void main(String[] args) {
            CellPhone cp = new CellPhone();
            cp.call();
            cp.message();
        }
    
    }
    
    // Animal.java
    interface Animal {
            //int x;
            //编译错误,x需要初始化,因为是 static final 类型
            int y = 5;
            public void eat();
            public void travel();
    }
    修饰符 interface A extends 接口1,接口2{
    
    }
    
    修饰符 class A implements 接口1,接口2{
    
    } 
    
    
    

    内部类(与嵌套类完全不是一个概念)

    内部类提供了更好的封装,可以把内部类隐藏在外部类之内,不允许同一个包中的其他类访问该类
    内部类的方法可以直接访问外部类的所有数据,包括私有的数据
    内部类所实现的功能使用外部类同样可以实现,只是有时使用内部类更方便
    内部类允许继承多个非接口类型(具体将在以后的内容进行讲解)
    public class animal {
    	public static String s="12345678";
    	public class dog
    	{
    		public void bark()
    		{
    			System.out.println("my s is"+s);
    		}
    	}
    	public static void main(String args[])
    	{
    		animal a=new animal();
    		dog b=a.new dog();
    		b.bark();
    	}
    }
    
    public class animal {
    	public static String s="12345678";
    	public String name="fuck";
    	public static class dog
    	{
    		public String name="what a";
    		public void bark()
    		{
    			System.out.println("my in name is"+name);
    			System.out.println("my out s is"+animal.s);
    			System.out.println("my out name is"+(new animal().name));
    		}
    	}
    	public static void main(String args[])
    	{
    		dog a=new dog();
    		a.bark();
    	}
    }
    
    	静态内部类不能直接访问外部类的非静态成员,但可以通过 new 外部类().成员 的方式访问
    如果外部类的静态成员与内部类的成员名称相同,可通过类名.静态成员访问外部类的静态成员;如果外部类的静态成员与内部类的成员名称不相同,则可通过成员名直接调用外部类的静态成员
    创建静态内部类的对象时,不需要外部类的对象,可以直接创建 内部类 对象名= new 内部类();
    连::运算符都被.代替了
    

    java还能有局部内部类,可以在方法中定义一个内部类
    匿名内部类,顾名思义,就是没有名字的内部类。正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写。但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口。

    // Outer.java
    public class Outer { 
    
        public Inner getInner(final String name, String city) { 
            return new Inner() { 
                private String nameStr = name; 
                public String getName() { 
                    return nameStr; 
                } 
            };
        } 
    
        public static void main(String[] args) { 
            Outer outer = new Outer(); 
            Inner inner = outer.getInner("Inner", "NewYork"); 
            System.out.println(inner.getName()); 
        } 
    } 
    interface Inner { 
        String getName(); 
    }
    
    

    注意java的class 后面不需要加分号,匿名的东西直接interface(相当于声明了一个原型),return new inner(){};大括弧内就正常定义这个类就可以了

    常用类

    import.java.util.Arrays

    import java.util.Arrays;
    import java.util.Random;
    public class Out
    {
    	public static void main(String args[])
    	{
    		int arr[]=new int[10];
    		//fill  填充
    		Arrays.fill(arr,9);
    		System.out.println("fill:"+Arrays.toString(arr));
    		Random random=new Random();
    		for(int i=0;i<arr.length;i++)
    		{
    			//随机
    			arr[i]=random.nextInt(101);
    			//这里是一个上开界,100以内的随机数
    		}
    		System.out.println("random:"+Arrays.toString(arr));
    		arr[5]=50;
    		Arrays.sort(arr);
    		System.out.println("sort:"+Arrays.toString(arr));
    		//二分搜索找返回下标
    		int i=Arrays.binarySearch(arr, 50);
    		System.out.println(i);
    		int newarr[]=Arrays.copyOf(arr,arr.length);
    		//复制
    		System.out.println("copy"+Arrays.toString(arr));
    	}
    }
    /*
    fill:[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
    random:[60, 57, 49, 60, 31, 97, 14, 7, 5, 33]
    sort:[5, 7, 14, 31, 33, 49, 50, 57, 60, 60]
    6
    copy[5, 7, 14, 31, 33, 49, 50, 57, 60, 60]*/
     */
     StringBuilder 是一种可以拼接字符串的类,拼接完成后可以用toString转化成字符串
     import java.util.Arrays;
    import java.util.Random;
    public class Out
    {
    	public static void main(String args[])
    	{
    		StringBuilder s = new StringBuilder("I");
    		s.append("java");
    		s.insert(1, "love");//原来处于1位的字符后移
    		System.out.println(s.toString());
    	}
    }
    //Ilovejava
    

    日历类

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    
    public class CalendarDemo {
        public static void main(String[] args) {
            System.out.println("完整显示日期时间:");
            // 字符串转换日期格式
            DateFormat fdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str = fdate.format(new Date());
            System.out.println(str);
    
            // 创建 Calendar 对象
            Calendar calendar = Calendar.getInstance();
            // 初始化 Calendar 对象,但并不必要,除非需要重置时间
            calendar.setTime(new Date());
    
            // 显示年份
            System.out.println("年: " + calendar.get(Calendar.YEAR));
    
            // 显示月份 (从0开始, 实际显示要加一)
            System.out.println("月: " + calendar.get(Calendar.MONTH));
    
    
            // 当前分钟数
            System.out.println("分钟: " + calendar.get(Calendar.MINUTE));
    
            // 今年的第 N 天
            System.out.println("今年的第 " + calendar.get(Calendar.DAY_OF_YEAR) + "天");
    
            // 本月第 N 天
            System.out.println("本月的第 " + calendar.get(Calendar.DAY_OF_MONTH) + "天");
    
            // 3小时以后
            calendar.add(Calendar.HOUR_OF_DAY, 3);
            System.out.println("三小时以后的时间: " + calendar.getTime());
            // 格式化显示
            str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime());
            System.out.println(str);
    
            // 重置 Calendar 显示当前时间
            calendar.setTime(new Date());
            str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime());
            System.out.println(str);
    
            // 创建一个 Calendar 用于比较时间
            Calendar calendarNew = Calendar.getInstance();
    
            // 设定为 5 小时以前,后者大,显示 -1
            calendarNew.add(Calendar.HOUR, -5);
            System.out.println("时间比较:" + calendarNew.compareTo(calendar));
    
            // 设定7小时以后,前者大,显示 1
            calendarNew.add(Calendar.HOUR, +7);
            System.out.println("时间比较:" + calendarNew.compareTo(calendar));
    
            // 退回 2 小时,时间相同,显示0
            calendarNew.add(Calendar.HOUR, -2);
            System.out.println("时间比较:" + calendarNew.compareTo(calendar));
    
            // calendarNew创建时间点
            System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendarNew.getTime()));
            // calendar创建时间点
            System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime()));
            System.out.println("时间比较:" + calendarNew.compareTo(calendar));
        }
    }
    编译运行:
    
    $ javac CalendarDemo.java
    $ java CalendarDemo
    完整显示日期时间:
    2018-12-12 15:50:49
    年: 2018
    月: 11
    分钟: 50
    今年的第 346天
    本月的第 12天
    三小时以后的时间: Wed Dec 12 18:50:49 CST 2018
    2018-12-12 18:50:49:449
    2018-12-12 15:50:49:455
    时间比较:-1
    时间比较:1
    时间比较:1
    2018-12-12 15:50:49:456
    2018-12-12 15:50:49:455
    时间比较:1
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class DateDemo {
        public static void main(String[] args) {
            String strDate, strTime;
            Date objDate = new Date();
            System.out.println("今天的日期是:" + objDate);
            long time = objDate.getTime();
            System.out.println("自1970年1月1日起以毫秒为单位的时间(GMT):" + time);
            strDate = objDate.toString();
            //提取 GMT 时间
            strTime = strDate.substring(11, (strDate.length() - 4));
            //按小时、分钟和秒提取时间
            strTime = "时间:" + strTime.substring(0, 8);
            System.out.println(strTime);
            //格式化时间
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(formatter.format(objDate));
        }
    }
    编译运行:
    
    $ javac DateDemo.java
    $ java DateDemo
    今天的日期是:Wed Dec 12 14:43:15 CST 2018
    自1970年1月1日起以毫秒为单位的时间(GMT):1544596995669
    时间:14:43:15
    2018-12-12 14:43:15
    

    MATH

    rint(double numvalue) double 返回最接近 numvalue 的整数值
    round(T arg) arg 为 double 时返回 long,为 float 时返回 int 返回最接近arg的整数值
    random 0.0到1.0的一个double值

    System

    System 使用示例
    在/home/project/目录下新建一个源代码文件SystemDemo.java
    
    import java.util.Arrays;
    
    public class SystemDemo {
        public static void main(String[] args) {
            int[] a = {7, 8, 9, 10, 11};
            int[] b = {1, 2, 3, 4, 5, 6};
            //从数组a的第二个元素开始,复制到b数组的第三个位置 复制的元素长度为3
            System.arraycopy(a, 1, b, 2, 3);
            //注意他是用前者覆盖后者
            //输出结果
            System.out.println(Arrays.toString(b));
            System.out.println("当前时间:" + System.currentTimeMillis());
            System.out.println("java版本信息:" + System.getProperty("java.version"));
            //运行垃圾收集器
            System.gc();
            //退出
            System.exit(0);
        }
    }
    
    编译运行:
    
    $ javac SystemDemo.java
    $ java SystemDemo
    [1, 2, 8, 9, 10, 6]
    当前时间:1544670501472
    java版本信息:11
    
    
    

    Random

    import java.util.Random;
    
    public class RandomDemo {
        public static void main(String[] args) {
            Random random = new Random();
            //随机生成一个整数 int范围
            System.out.println(random.nextInt());
            //生成 [0,n] 范围的整数  设n=100
            System.out.println(random.nextInt(100 + 1));
            //生成 [0,n) 范围的整数  设n=100
            System.out.println(random.nextInt(100));
            //生成 [m,n] 范围的整数  设n=100 m=40
            System.out.println((random.nextInt(100 - 40 + 1) + 40));
            //随机生成一个整数 long范围
            System.out.print(random.nextLong());
            //生成[0,1.0)范围的float型小数
            System.out.println(random.nextFloat());
            //生成[0,1.0)范围的double型小数
            System.out.println(random.nextDouble());
        }
    }
    

    泛型

    /*
    使用T代表类型,无论何时都没有比这更具体的类型来区分它。如果有多个类型参数,我们可能使用字母表中T的临近的字母,比如S。
    */
    class Test<T> {
        private T ob;
    
        /*
        定义泛型成员变量,定义完类型参数后,可以在定义位置之后的方法的任意地方使用类型参数,就像使用普通的类型一样。
        注意,父类定义的类型参数不能被子类继承。
        */
    
        //构造函数
        public Test(T ob) {
            this.ob = ob;
        }
    
        //getter 方法
        public T getOb() {
            return ob;
        }
    
    
        //setter 方法
        public void setOb(T ob) {
            this.ob = ob;
        }
    
        public void showType() {
            System.out.println("T的实际类型是: " + ob.getClass().getName());
            
        }
    }
    
    public class TestDemo {
        public static void main(String[] args) {
            // 定义泛型类 Test 的一个Integer版本
            Test<Integer> intOb = new Test<Integer>(88);
            intOb.showType();
            int i = intOb.getOb();
            System.out.println("value= " + i);
            System.out.println("----------------------------------");
            // 定义泛型类Test的一个String版本
            Test<String> strOb = new Test<String>("Hello Gen!");
            strOb.showType();
            String s = strOb.getOb();
            System.out.println("value= " + s);
        }
    }
    编译运行:
    
    $ javac TestDemo.java
    $ java TestDemo
    T的实际类型是: java.lang.Integer
    value= 88
    ----------------------------------
    T的实际类型是: java.lang.String
    value= Hello Gen!
    
    

    确定ob的实际类型只需要getClass().getName()

    java STL

    https://www.shiyanlou.com/courses/1230/labs/9469/document
    具体用法看这里
    1.toString 可以重载,相当于重载cout
    2.ArrayList类的一些方法,add(node),add(0,node)在第0个位置插入node,get(i)得到的i个node
    3.addAll(arr),addAll(0,arr)插入整个node数组
    size()大小
    遍历的方法

    /**
         * 通过迭代器来遍历
         * 迭代器的工作是遍历并选择序列中的对象,Java 中 Iterator 只能单向移动
         */
        public void testIterator() {
            // 通过集合的iterator方法,取得迭代器实例
            Iterator<Student> it = students.iterator();
            System.out.println("有如下学生(通过迭代器访问):");
            while (it.hasNext()) {
    
                Student st = it.next();
                System.out.println("学生" + st.id + ":" + st.name);
            }
        }
    
        /**
         * 通过for each 方法访问集合元素
         *
         */
        public void testForEach() {
            System.out.println("有如下学生(通过for each):");
            for (Student obj : students) {
                Student st = obj;
                System.out.println("学生:" + st.id + ":" + st.name);
            }
            //使用java8 Steam将学生排序后输出
            students.stream()//创建Stream
                    //通过学生id排序
                    .sorted(Comparator.comparing(x -> x.id))
                    //输出
                    .forEach(System.out::println);
        }
     /**
         * 修改List中的元素
         *
         */
        public void testModify() {
            students.set(4, new Student("3", "吴酒"));
        }
    
        /**
         * 删除List中的元素
         *
         */
        public void testRemove() {
            Student st = students.get(4);
            System.out.println("我是学生:" + st.id + ":" + st.name + ",我即将被删除");
            students.remove(st);
            System.out.println("成功删除学生!");
            testForEach();
        }
    
    
    

    Map

    public Map<String,Course>courses;//Map也是一个接口
    courses = new HashMap<String,Course>();
    get(first)通过first获得second,如果没有返回null,这个时候才可以把映射插入集合 注意判定
    course.put(Id,newcourse) put方法可以加入进去
    遍历方法

      public void testKeySet() {
            //通过 keySet 方法,返回 Map 中的所有键的 Set 集合
            Set<String> keySet = courses.keySet();
            //遍历 keySet,取得每一个键,在调用 get 方法取得每个键对应的 value
            for(String crID: keySet) {
                Course cr = courses.get(crID);
                if(cr != null){
                    System.out.println("课程:" + cr.name);
                }
            }
        }
    public void testEntrySet() {
            //通过 entrySet 方法,返回 Map 中的所有键值对
            Set<Entry<String,Course>> entrySet = courses.entrySet();
            for(Entry<String,Course> entry: entrySet) {
                System.out.println("取得键:" + entry.getKey());
                System.out.println("对应的值为:" + entry.getValue().name);
            }
        }
    
    
    

    courses.remove(ID)删除映射
    courses.put(crID, newCourse);修改原来crID所对应的映射

    异常

    异常通常有四类:
    
    Error:系统内部错误,这类错误由系统进行处理,程序本身无需捕获处理
    Exception:可以处理的异常
    RuntimeException:可以捕获,也可以不捕获的异常
    继承 Exception 的其他类:必须捕获,通常在 API 文档中会说明这些方法抛出哪些异常
    平时主要关注的异常是 Exception 下的异常,而 Exception 异常下又主要分为两大类异常,一个是派生于 RuntimeExcption 的异常,一个是除了 RuntimeExcption 体系之外的其他异常。
    
    RuntimeExcption 异常(运行时异常)通常有以下几种:
    
    错误的类型转换
    数组访问越界
    访问 null 指针
    算术异常
    一般来说,RuntimeException 都是程序员的问题。
    
    非 RuntimeException(受查异常)一般有:
    
    打开一个不存在的文件
    没有找到具有指定名称的类
    操作文件异常
    受查异常是编译器要求必须处理的异常,必须使用try catch处理,或者向上抛出,给上层处理
    
    

    throw new 异常名()

    throws 声明异常
    throws 用于声明异常,表示该方法可能会抛出的异常。如果声明的异常中包括 checked 异常(受查异常),那么调用者必须处理该异常或者使用 throws 继续向上抛出。throws 位于方法体前,多个异常使用,分割。
    
    修改/home/project/下的ThrowsTest.java
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    
    public class ThrowsTest {
    
        public static void main(String[] args) throws FileNotFoundException {
            //由方法的调用者捕获异常或者继续向上抛出
            throwsTest();
    
        }
    
        public static void throwsTest() throws FileNotFoundException {
            new FileInputStream("/home/project/shiyanlou.file");
        }
    }
    

    对于上述三个关键词所构成的语句块,try语句块是必不可少的,catch和finally语句块可以根据情况选择其一或者全选。你可以把可能发生错误或出现问题的语句放到try语句块中,将异常发生后要执行的语句放到catch语句块中,而finally语句块里面放置的语句,不管异常是否发生,它们都会被执行。
    try
    catch(){}// 三部曲,catch的括号里面可以放一个异常的对象,大括弧调用对象的printStackTrace
    异常调用堆栈:main 调用f,f调用g,g抛出异常,那么pst就可以输出这个线路

    可以在try中放许多catch,把不同的异常一一捕获,根据异常的种类可以一一捕获

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    
    public class MultipleCapturesDemo {
        public static void main(String[] args) {
            try {
                new FileInputStream("");
            } catch (FileNotFoundException e) {
                System.out.println("IO 异常");
            } catch (Exception e) {
                System.out.println("发生异常");
            }
        }
    }
    
    

    finally

    自定义异常

    只要让它集成Exception或其子类就可以

    // MyAriException.java
    public class MyAriException extends ArithmeticException {
        //自定义异常类,该类继承自ArithmeticException
    
        public MyAriException() {
    
        }
        //实现默认的无参构造方法
    
        public MyAriException(String msg) {
            super(msg);
        }
        //实现可以自定义输出信息的构造方法,将待输出信息作为参数传入即可
    }
    
    添加一个ExceptionTest类作为测试用,在该类的main()方法中,可以尝试使用throw抛出自定义的异常。
    
    代码片段如下:
    
    // ExceptionTest.java
    import java.util.Arrays;
    
    public class ExceptionTest {
        public static void main(String[] args) {
            int[] array = new int[5];
            //声明一个长度为5的数组
    
            Arrays.fill(array, 5);
            //将数组中的所有元素赋值为5
    
            for (int i = 4; i > -1; i--) {
                //使用for循环逆序遍历整个数组,i每次递减
    
                if (i == 0) {
                // 如果i除以了0,就使用带异常信息的构造方法抛出异常
    
                    throw new MyAriException("There is an exception occured.");
                }
    
                System.out.println("array[" + i + "] / " + i + " = " + array[i] / i);
                // 如果i没有除以0,就输出此结果
            }
        }
    }
    
    

    Lambda

    interface一个接口,里面放一些函数原型(函数名是operation),定义一些接口的式子
    (参数列表)->表达式/大括弧+return

    public class LamdbaTest {
        public static void main(String args[]){
            LamdbaTest tester = new LamdbaTest();
    
              // 带有类型声明的表达式
              MathOperation addition = (int a, int b) -> a + b;
    
              // 没有类型声明的表达式
              MathOperation subtraction = (a, b) -> a - b;
    
              // 带有大括号、带有返回语句的表达式
              MathOperation multiplication = (int a, int b) -> { return a * b; };
    
              // 没有大括号和return语句的表达式
              MathOperation division = (int a, int b) -> a / b;
    
              // 输出结果
              System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
              System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
              System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
              System.out.println("10 / 5 = " + tester.operate(10, 5, division));
    
              // 没有括号的表达式            
              GreetingService greetService1 = message ->
              System.out.println("Hello " + message);
    
              // 有括号的表达式            
              GreetingService greetService2 = (message) ->
              System.out.println("Hello " + message);
    
              // 调用sayMessage方法输出结果
              greetService1.sayMessage("Shiyanlou");
              greetService2.sayMessage("Classmate");
           }
    
           // 下面是定义的一些接口和方法
    
           interface MathOperation {
              int operation(int a, int b);
           }
    
           interface GreetingService {
              void sayMessage(String message);
           }
    
           private int operate(int a, int b, MathOperation mathOperation){
              return mathOperation.operation(a, b);
           }
    }
    
    # 
    
    只有createNewFile能够成功创建文件
    import java.io.*;
    
    
    public class Fuck {
    	
    	public static void main(String args[])
    	{
    		File f1=new File("C:\Users\tony\Desktop\笔记\JAVA代码\1","1.txt");
    		File f2=new File(f1,"2.txt");
    		try {
    			System.out.println(f1.createNewFile());
    			
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    		File[]files=File.listRoots();
    		for(File file:files)
    		{
    			System.out.println(file);
    			if(file.length()>0)
    			{
    				String[]filenames=file.list();
    				for(String filename:filenames)
    				{
    					System.out.println(filename);
    				}
    			}
    		}
    
    
    	}
    }
    import java.io.*;
    public class Fuck
    {
    	public static void main(String args[])
    	{
    		try {
    			File in = new File("D:\textbase\1.txt");
    			File out =new File("D:\textbase\2.txt");
    			FileInputStream fis=new FileInputStream(in);
    			FileOutputStream fos=new FileOutputStream(out);
    			int c;
    			while((c=fis.read())!=-1)
    			{
    				fos.write(c);
    			}
    			fis.close();
    			fos.close();
    			
    		}catch(FileNotFoundException e)
    		{
    			System.out.println("FileStreamtest:"+e);
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}	
    	}
        ///java要求必须处理IOException,不会出任何错误,但是贼几把麻烦啊啊啊啊啊啊
    r:只读,任何写操作都讲抛出 IOException
    rw:读写,文件不存在时会创建该文件,文件存在是,原文件内容不变,通过写操作改变文件内容。
    rws:打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。
    rwd:打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到底层存储设备。
    import java.io.*;
    import java.io.RandomAccessFile;
    public class Fuck
    {
    	public static void main(String args[])
    	{
    		int arr[]= {1,2,3,44,55};
    		try {
    			RandomAccessFile randf = new RandomAccessFile("D:/textbase/1.txt","rw");
    			for(int i=0;i<arr.length;i++)
    			{
    				randf.writeInt(arr[i]);
    			}
    			for(int i=arr.length-1;i>=0;i--)
    			{
    				randf.seek(i*4L);
    				System.out.println(randf.readInt());
    			}
    			randf.close();
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
    
    import java.io.*;
    import java.io.RandomAccessFile;
    import java.nio.file.*;//只import nio.*是没有用的
    import java.nio.file.Paths;
    import java.nio.file.StandardCopyOption;
    public class Fuck
    {
    ​	public static void main(String args[])
    ​	{
    ​		
    		try {
    			Files.copy(Paths.get("D:/textbase/1.txt"),Paths.get("D:/textbase/2.txt"),StandardCopyOption.REPLACE_EXISTING);
    			
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
    
    import java.io.*;
    import java.io.RandomAccessFile;
    import java.nio.file.*;
    import java.nio.file.Paths;
    import java.nio.file.StandardCopyOption;
    public class Fuck
    {
    	public static void main(String args[])
    	{
    		
    		try {
    //这里就改了一个move,把1.txt重命名后移动到另一个区域			Files.move(Paths.get("D:/textbase/1.txt"),Paths.get("2.txt"),StandardCopyOption.REPLACE_EXISTING);
    			
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
    删除文件的三种方法
    //删除文件,文件必须存在,否则抛出异常
                Files.delete(Paths.get("/home/project/3.txt"));
                //删除文件,返回是否删除成功 即使文件不存在,也不会保存,直接返回false
                System.out.println(Files.deleteIfExists(Paths.get("/home/project/3.txt")));
                //或者使用File类的delete方法
                File file = new File("/home/project/4.txt");
                System.out.println(file.delete());
    File file=new File("1.txt");
    		System.out.println("文件或者目录名:" + file.getName());
            System.out.println("绝对路径:" + file.getAbsolutePath());
            System.out.println("父目录:" + file.getParent());
            System.out.println("文件路径:" + file.getPath());
            //判断文件是否是目录
            if (file.isDirectory()) {
                //打印目录中的文件
                Arrays.stream(file.list()).forEach(System.out::println);
            }
            System.out.println("是否隐藏:" + file.isHidden());
            System.out.println("是否存在:" + file.exists());
    文件或者目录名:1.txt
    绝对路径:C:Users	onyDesktop笔记JAVA代码11.txt
    父目录:null
    文件路径:1.txt
    是否隐藏:false
    是否存在:false        
    public class Fuck
    {
    	public static void main(String args[])
    	{
    		readDir(new File("C:\Users\tony\Desktop\笔记"),0);
    		
    	}
    	static void readDir(File file,int k)
    	{
    		if(file==null)
    			return ;
    		if(file.isDirectory())
    		{
    			File files[];
    			if((files=file.listFiles())!=null)
    			{
    				for(File file1:files)
    				{
    					readDir(file1,k+1);
    				}
    			}
    		}
    		else {
    			for(int i=0;i<k;i++)
    			{
    				System.out.print("  ");
    			}
    			System.out.println(file.getName());
    		}
    	}
    }
    

    IO流

    字节流:表示以字节为单位从 stream 中读取或往 stream 中写入信息。通常用来读取二进制数据。
    字符流:以 Unicode 字符为单位从 stream 中读取或往stream 中写入信息。

    public class Fuck
    {
    	public void copy(InputStream in,OutputStream out)throws IOException
    	{
    		byte[]buf =new byte[4096];
    		int len=in.read(buf);
    		while(len!=-1)
    		{
    			out.write(buf,0,len);
    			len=in.read(buf);
    		}
    	}
    	public static void main(String args[])throws IOException
    	{
    		Fuck f = new Fuck();
    		System.out.println("please in put a char");
    		f.copy(System.in,System.out);
    	}
    	
    }
    

    以上可以模拟字节流

    使用缓冲流提高效率
    public class Fuck
    {
    	public static void main(String args[])
    	{
    		try
    		{
    			FileInputStream fis = new FileInputStream("2.txt");
    			InputStreamReader dis = new InputStreamReader(fis);
    			BufferedReader reader=new BufferedReader(dis);
    			String s;
    			while((s=reader.readLine())!=null)
    			{
    				System.out.println("read"+s);
    			}
    			dis.close();
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
    

    IO 集合先跳过一些内容

    JDBC

    学MYsql再学
    注定无法全都学完啊

    正则表达式学不会

    Swing

    package Fuck;

    import javax.swing.JFrame;

    public class Window extends JFrame {
    ​ //此处通过继承JFrame类来使我们自己的MySwingWindow具有窗体的一些属性和方法

    public Window(){
        //在窗体的构造方法中设置窗体的各项属性
    
        super();
        //使用 super() 来引用父类的成分,用 this 来引用当前对象
    
        this.setSize(400, 300);
        //设置窗体的大小
    
        this.getContentPane().setLayout(null);
        //返回此窗体的 contentPane 对象,设置其布局
        //这一句不太懂的话也不用担心,先写着
    
        this.setTitle("My First Swing Window");
        //设置窗体的标题
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        Window window = new Window();
        //声明一个窗体对象 window
    
        window.setVisible(true);
        //设置这个窗体是可见的
    }
    

    }
    package Fuck;

    import java.awt.;
    import javax.swing.
    ;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;

    public class Window extends JFrame {
    ​ private JLabel m1;
    ​ private JTextField m2;
    ​ private JButton m3;
    ​ //此处通过继承JFrame类来使我们自己的MySwingWindow具有窗体的一些属性和方法

    public Window(){
        //在窗体的构造方法中设置窗体的各项属性
    
        super();
        //使用 super() 来引用父类的成分,用 this 来引用当前对象
    
        this.setSize(400, 300);
        //设置窗体的大小
    
        this.getContentPane().setLayout(null);
        //返回此窗体的 contentPane 对象,设置其布局
        //这一句不太懂的话也不用担心,先写着
    
        this.setTitle("My First Swing Window");
        //设置窗体的标题
        this.add(getJLabel(),null);
        this.add(getJTextField(),null);
        this.add(getJButton(),null);
        
    }
    private JLabel getJLabel()
    {
    	if(m1==null)
    	{
    		m1 = new JLabel();
    		m1.setBounds(5,10,250,30);
    		//x y width height
    		m1.setText("Fuck you leather man");
    	
    	}
    	return m1;
    }
    private JTextField getJTextField()
    {
    	if(m2==null)
    	{
    		m2 = new JTextField();
    		m2.setBounds(5,45,200,30);
    		//x y width height
    		m2.setText("Fuck you sb");
    	
    	}
    	return m2;
    }
    private JButton getJButton()
    {
    	if(m3==null)
    	{
    		m3 = new JButton();
    		m3.setBounds(5,80,300,40);
    		m3.setText("Click me and I will hit your ass!");
            //设定它要显示的字符串
            m3.addActionListener(new ActionListener() {
                //为其添加一个事件监听,从而使这个按钮可以响应用户的点击操作
                //ActionListener是用于接收操作事件的侦听器接口。
                //对处理操作事件感兴趣的类可以实现此接口,而使用该类创建的对
                //可使用组件的 addActionListener 方法向该组件注册。
                //在发生操作事件时,调用该对象的 actionPerformed 方法。
    
                public void actionPerformed(ActionEvent e) {
                    //该方法会在发生操作时被调用,我们要做的事情就可以写在这里面
                    //比如我们下面要做的事情就是改变之前两个控件里面的文字颜色和背景色
    
                    m1.setForeground(Color.RED);
                    //设置此组件的前景色。
    
                    m2.setBackground(Color.BLUE);
                    //设置此组件的背景色。
                }
            });
        }
    




    return m3;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        Window window = new Window();
        //声明一个窗体对象 window
    
        window.setVisible(true);
        //设置这个窗体是可见的
    }
    

    }

  • 相关阅读:
    如何在ONENET云端搭建IOT平台
    01_接口测试介绍
    10_fiddler_待整理
    09_fiddler_慢网络测试(限制网速)
    08_Fiddler_打断点(bpu)
    07_Fiddler_post提交到主体的四种参数形式
    06_Fiddler_get请求(url详解)
    05_Fiddler的Script 脚本用法
    04_Fiddler_Composer创建和发送HTTP Request
    03_Fiddler抓包的捕获设置
  • 原文地址:https://www.cnblogs.com/Tony100K/p/11608379.html
Copyright © 2011-2022 走看看