java基础自用学习笔记

基本的Dos命令

一. 四种打开 CMD 控制台的方式

  1. Win键+R,输入cmd打开控制台
    在这里插入图片描述
  2. 开始–>Windows系统–>命令提示符

  1. 在任意文件夹下,按住shift键+鼠标右键点击,在此处打开命令行窗口
    在这里插入图片描述
  2. 资源管理器的地址栏前面加上 cmd 路径在这里插入图片描述

二. 管理员方式运行

用第二种方式,鼠标右键点击选择管理员方式运行在这里插入图片描述

三. 常见的Dos命令

  1. 盘符切换
    在这里插入图片描述

  2. 查看当前目录下的所有文件: dir命令
    在这里插入图片描述

  3. 切换目录 : cd (change directory)命令

    跨盘操作 :cd /d

    本盘操作 :cd

在这里插入图片描述
4. 返回上一级目录 : cd…命令
在这里插入图片描述
5. 清理屏幕: cls(clear screen) 命令
6. 退出终端: exit命令
7. 查看电脑的ip: ipconfig命令
在这里插入图片描述
8. 打开计算器:calc(calculator)命令在这里插入图片描述
9. 打开画图板:mspaint命令
10. 打开记事本:notepad命令在这里插入图片描述

  1. ping命令,用于测试网络是否正常
    在这里插入图片描述

  2. CMD窗口中,鼠标右键就是粘贴

  3. 在桌面创建文件夹:md 文件夹名字在这里插入图片描述

  4. 创建文件:cd> 文件名在这里插入图片描述

  5. 删除文件:del命令
    在这里插入图片描述

  6. 删除文件夹:rd命令(删除后回收站里也没有了)在这里插入图片描述

Hello World(记事本)

  1. 随便新建一个文件夹,存放代码
    在这里插入图片描述

  2. 新建一个java文件

    1. 文件后缀名为.java
    2. Hello.java

在这里插入图片描述
4. 编写代码

public class Hello{
	public static void main(String[] args){
		System.out.print("Hello,World!");
	}
}
  1. 编译java.c java文件,会生成一个class文件
  2. 运行class文件,java class文件

在这里插入图片描述

可能遇到的情况

  1. 每个单词的大小写不能出现问题,Java是大小写敏感的
  2. 尽量输出结果为英文,因为cmd可能对汉字乱码;
  3. 文件名和类名必须保持一致,并且首字母大写
  4. 符号使用要使用英文

Hello World(IntelliJ IDEA)

新建项目
在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述
右键src
在这里插入图片描述
填写完类名,按回车
在这里插入图片描述
输入psvm,自动提示填写public static void main(String[] args) {}
在这里插入图片描述
输入sout,自动提示填写System.out.println();
在这里插入图片描述
跑程序,点击小三角按钮,选择第一项,也可以用快捷键ctrl+shift+F10。
在这里插入图片描述
输出成功!
在这里插入图片描述

变量

  1. 变量就是可以变化的量。
  2. 数据类型 变量名 = 值 ;可以使用逗号隔开来声明多个同类型变量;但不建议这么做,因为可读性低。
  3. java 是一种强类型语言,每个变量都必须声明其类型。
  4. Java 变量是程序中最基本的存储单元,其要素包括变量名,变量类型和作用域。
  5. 每个变量都有类型,类型可以是基本类型,也可以是引用类型。
  6. 变量名必须是合法的标识符。
  7. 变量声明是一条完整的语句,因此每一个声明都必须以分号结束。
    在这里插入图片描述

局部变量

局部变量只能在该方法下使用,类似下图图示。
在这里插入图片描述
在这里插入图片描述

实例变量

实例变量:从属于对象;如果不自行初始化,这个类型的默认值为 0或0.0 ;布尔值默认值是false;除了基本类型,其余的默认值都是null。
在这里插入图片描述

类变量

类变量 static
在这里插入图片描述

常量

  1. 常量是指初始化后不能再改变值!不会变动的值。
  2. 所谓常量可以理解成一种特殊的变量,它的值被设定后,在程序运行过程中不允许被改变。
  3. 常量名一般使用大写字符。
  4. final 常量名 = 值 ;修饰符,不存在先后顺序
    在这里插入图片描述
    在这里插入图片描述

命名规范

  1. 所有变量、方法、类名:见明知意!
  2. 类成员变量:首字母小写和驼峰原则:monthSalary,lastName。
  3. 局部变量:首字母小写和驼峰原则。
  4. 常量:大写字母和下划线:MAX_VALUE。
  5. 类名:首字母大写和驼峰原则:Man,GoodMan。
  6. 方法名:首字母小写和驼峰原则:run(),runRun()。

字节

  1. 位(bit):是计算机内部数据存储的最小单位,11001100是一个八位二进制数。
  2. 字节(byte):是计算机中数据处理的基本单位,习惯上用大写B来表示。
  3. 1B(byte,字节)= 8 bit(位)。
  4. 字符:是指计算机中使用的字母、数字、字和符号。
  5. 1bit表示1位;1Byte表示一个字节 1B=8b;1024B=1M;1024KB=1M;1024M=1G。

进制

public static void main(String[] args) {
        //整数扩展:进制  十进制   二进制0b  八进制0   十六进制0x;
        int i = 10;    //十进制
        int i1 = 0b10; //二进制0b
        int i2 = 010;  //八进制0
        int i3 = 0x10; //十六进制0x
        System.out.println("10的十进制" + i);
        System.out.println("10的二进制" + i1);
        System.out.println("10的八进制" + i2);
        System.out.println("10的十六进制" + i3);
        System.out.println("==========================================");

        
        
        //浮点数扩展:最好不要用浮点数进行比较;用BigDecimal数学工具类
        //float 是离散的,有限的,舍入误差,大约数,接近但不等于
        float f = 0.1f;
        double d = 1.0/10;
        System.out.println(f==d);//相等输出true,不相等输出false
        float x = 2312345135235153151f;
        float y = x + 1 ;
        System.out.println(x==y);
        System.out.println("==========================================");

        
        
        //字符拓展:所有字符的本质还是数字
        char c1 = 'a';
        char c2 = '中';
        System.out.println(c1);
        System.out.println((int)c1);//强制转换成int型
        System.out.println(c2);
        System.out.println((int)c2);//强制转换成int型
        System.out.println("==========================================");
        char c3 = '\u0061';// a
        System.out.println(c3);
        System.out.println("Hello\tWorld");//"\t"为制表符
        System.out.println("Hello\nWorld");//"\n"为换行
        System.out.println("==========================================");


        String s1 = new String("hello world");
        String s2 = new String("hello world");
        System.out.println(s1==s2);//相等输出true,不相等输出false;比较的是地址
        String s3 = "hello world";
        String s4 = "hello world";
        System.out.println(s3==s4);//相等输出true,不相等输出false;比较的是值
        System.out.println("==========================================");

        //布尔值扩展
        boolean flag = true ;
        if (flag==true){//这句和下面的 if 语句意思一样
            System.out.println("1");
        } 
        if(flag){//Less is More!  代码要精简易读
            System.out.println("2");
        }        
    }

在这里插入图片描述

数据类型

基本数据类型

public static void main(String[] args) {
    //单行注释
    /*
    多行注释
    Java语言将数据类型分为:
        基本数据类型:
            数值型:
                整型:byte(1个字节,字节型)、short(2个字节,短整型)、int(4个字节,普通整型)、long(8个字节,长整型)
                浮点型:float(4个字节,单精度浮点数)、double(8个字节,双精度浮点数)
            字符型:char
            布尔型:boolean
        引用类型
     */
        int x = 10 , y = 1; // 使用变量需要进行初始化(赋值)
        float f1 = 3.1415926f;
        char ch1 = 'a' , ch2 = '是', ch3 = 'B',ch4 = '?';
        boolean b1 = true , b2 = false;
        System.out.println("x = " + x);
        System.out.println("y = " + y);
        System.out.println("f1 = " + f1);
        System.out.println("char可以是任何单个字符;" + ch1 + ch2 + ch3 + ch4);
    }

在这里插入图片描述

public static void main(String[] args) {
        //八大基本数据类型

        //整数类型
        int num1 = 10;//int占4个字节范围:-2147483648 至 2147483647
        byte num2= 20;//byte占1个字节范围:-128 至 127
        short num3 = 30;//short占2个字节范围:-32768 至 32767
        long num4 = 40;//long占8个字节范围:-9223372036854775808 至 9223372036854775807
        System.out.println("================整数类型===============");
        System.out.println(num1);
        System.out.println(num2);
        System.out.println(num3);
        System.out.println(num4);

        //小数:浮点类型
        float num5 = 50.1F;//float占4个字节
        double num6 =3.1415926;//double占8个字节
        System.out.println("================浮点数类型===============");
        System.out.println(num5);
        System.out.println(num6);

        //字符类型
        char name1 = '国';//char占2个字节
        System.out.println("================字符类型===============");
        System.out.println(name1);

        //字符串,String不是关键字,是类
        String name2 ="干得漂亮";
        System.out.println("================字符串===============");
        System.out.println(name2);

        //布尔值:是与否;占一位其值只有true和false两个
        boolean flag = true;//
        //boolean flag = false;
        System.out.println("================布尔值===============");
        System.out.println(flag);
    }

在这里插入图片描述

引用类型,包装器类型,字符串

除去八个基本类型,其他都是引用类型

public static void main(String[] args) {
        // 引用类型:排除八个基本数据类型,其他的都是引用类型
        // Java中的关键字都是小写字母
        // Java不是完全体的面向对象语言,它保留了八个基本数据类型
        // 面向对象最基本的单元是类,八个基本数据类型不是类
        // 为了弥补这个问题,为八个基本数据类型定义了八个包装器类型
        // 基本数据类型 int       short      byte    long     float   double     char         boolean
        // 包装器类型   Integer   Short      Byte    Long     Float   Double     Character    Boolean
        Float f1 = 100.23F;//自动装箱, 这里的f1不是基本的数据类型
        Float f2 = new Float(5.6);// 手动装箱, new 关键字的主要作用是调用构造方法创建一个类的实例
        float f3 = 100.23F;
        System.out.println(Integer.MAX_VALUE);// 输出 int 类型能够表示的最大值
        int x = Integer.valueOf("1000");// 将字符串转换数值类型
        System.out.println(x + 2000);

        // String 字符串 StringBuilder & StringBuffer
        String str = "Hello Muqi" + "!";
        System.out.println(str);
        //字符串中字符的索引从0开始
        System.out.println(str.charAt(6));//第六位的字符
        System.out.println(str.toUpperCase());//所有字母转换大写
        System.out.println(str.toLowerCase());//所有字母转换小写
        System.out.println(str.indexOf('l'));//返回某个字符第一次出现的索引
        String s1 = "X09y", s2 ="x09y";
        System.out.println(s1.equals(s2));
        System.out.println(s1.equalsIgnoreCase(s2));//忽略大小写的比较
        System.out.println(str.substring(6,9));

    }

在这里插入图片描述

运算符

public static void main(String[] args) {
        /*
        Java语言支持的运算符有:
            算术运算符  + - * / %
            比较运算符  < > == != >= <=
            逻辑运算符  & | ! && ||
            算术赋值运算符  = += -= *= /= %=
            条件运算符  A ? B : C
            位运算符  & | ^ >> << >>> ~
         */




        //算数运算符
        //Java 语言算术运算符的优先级是先乘除后加减。
        //浮点型和双精度型返回的结果都带有小数,字符型将会把字符转换为 ASCII 码再运算。
        //整数之间的运算结果只保留整数部分,浮点型运算时保留 6 位小数部分,双精度运算时则保留 16 位小数部分。
        float f1 = 9 % 4;// 保存取余后浮点类型的结果
        double da = 9 + 4.5; // 双精度加法
        double db = 9 - 3.0; // 双精度减法
        double dc = 9 * 2.5; // 双精度乘法
        double dd = 9 / 3.0; // 双精度除法
        double de = 9 % 4; // 双精度取余
        System.out.println("=======================算数运算符=======================");
        System.out.println("整数的算术运算"); // 整数的加、减、乘、除和取余
        System.out.printf("9+4=%d \n", 9 + 4);
        System.out.printf("9-4=%d \n", 9 - 4);
        System.out.printf("9*4=%d \n", 9 * 4);
        System.out.printf("9/4=%d \n", 9 / 4);
        System.out.printf("9%%4=%d \n", 9 % 4);
        System.out.println("浮点数的算术运算"); // 浮点数的加、减、乘、除和取余
        System.out.printf("9+4.5f=%f \n", 9 + 4.5f);
        System.out.printf("9-3.0f=%f \n", 9 - 3.0f);
        System.out.printf("9*2.5f=%f \n", 9 * 2.5f);
        System.out.printf("9/3.0f=%f \n", 9 / 3.0f);
        System.out.printf("9%%4=%f \n", f1);
        System.out.println("双精度数的算术运算"); // 双精度数的加、减、乘、除和取余
        System.out.printf("9+4.5=%4.16f \n", da);
        System.out.printf("9-3.0=%4.16f \n", db);
        System.out.printf("9*2.5=%4.16f \n", dc);
        System.out.printf("9/3.0=%4.16f \n", dd);
        System.out.printf("9%%4=%4.16f \n", de);
        System.out.println("字符的算术运算"); // 对字符的加法和减法
        System.out.printf("'A'+32=%d \n", 'A' + 32);
        System.out.printf("'A'+32=%c \n", 'A' + 32);
        System.out.printf("'a'-'B'=%d \n", 'a' - 'B');




        //比较运算符(关系运算符)
        //关系运算符的优先级为:>、<、>=、<= 具有相同的优先级,并且高于具有相同优先级的 !=、==。
        //关系运算符的优先级高于赋值运算符而低于算术运算符,结合方向是自左向右。
        int x = 20 , y = 2, z = 2;
        System.out.println("=======================比较运算符=======================");
        System.out.println("小于:x < y :" + (x < y));
        System.out.println("大于:x > y :" + (x > y));
        System.out.println("相等:x == y :" + (x == y));
        System.out.println("不等:x != y :" + (x != y));
        System.out.println("大于等于:z >= y :" + (z >= y));
        System.out.println("小于等于:z <= y :" + (z <= y));




        //逻辑运算符
        //逻辑运算符的优先级为:!运算级别最高,&& 运算高于 || 运算。
        //!运算符的优先级高于算术于运算符,而 && 和 || 运算则低关系运算符。
        //结合方向是:逻辑非(单目运算符)具有右结合性,逻辑与和逻辑或(双目运算符)具有左结合性。
        //&&	a&&b	短路与	ab 全为 true 时,计算结果为 true,否则为 false。
        //||	a||b	短路或	ab 全为 false 时,计算结果为 false,否则为 true。
        //!	    !a	    逻辑非	a 为 true 时,值为 false,a 为 false 时,值为 true
        //|	    a|b	    逻辑或	ab 全为 false 时,计算结果为 false,否则为 true
        //&	    a&b	    逻辑与	ab 全为 true 时,计算结果为 true,否则为 false
        boolean b1 = true , b2 = false;
        System.out.println("=======================逻辑运算符=======================");
        System.out.println((y == z) & b1);
        System.out.println((y == z) | b2);
        System.out.println(!b1);
        System.out.println((x == y) && b1);
        System.out.println((x == y) && b2);
        //&& 与 & 区别:如果 a 为 false,则不计算 b(因为不论 b 为何值,结果都为 false)
        //|| 与 | 区别:如果 a 为 true,则不计算 b(因为不论 b 为何值,结果都为 true)
        //短路与(&&)和短路或(||)能够采用最优化的计算方式,从而提高效率。在实际编程时,应该优先考虑使用短路与和短路或。




        //算术赋值运算符
        int a = 1, b = 2;
        System.out.println("=======================算数赋值运算符=======================");
        a += b; // 相当于 a = a + b
        System.out.println(a);
        a += b + 3; // 相当于 a = a + b + 3
        System.out.println(a);
        a -= b; // 相当于 a = a - b
        System.out.println(a);
        a *= b; // 相当于 a=a*b
        System.out.println(a);
        a /= b; // 相当于 a=a/b
        System.out.println(a);
        a %= b; // 相当于 a=a%b
        System.out.println(a);




        //条件运算符
        // 可以将条件运算符理解为 if-else 语句的简化形式
        // 在使用较为简单的表达式时,使用该运算符能够简化程序代码,使程序更加易读。
        int c = 6,d = 2,e;
        System.out.println("=======================条件运算符=======================");
        // 首先要判断 c>d 表达的值,如果为 true,e 的值为 c-d;否则 e 的值为 c+d。
        // 很明显 c>d 表达式结果为 true,所以 e 的值为 4。
        e = c>d ? c-d : c+d;
        System.out.println(e);




        //位运算符
        int num1 = 100 & 0;
        System.out.println("=======================位运算符=======================");
        // 参与运算的数字,低位对齐,高位不足的补零。
        // 如果对应的二进制位同时为 1,那么计算结果才为 1,否则为 0。
        // 因此,任何数与 0 进行按位与运算,其结果都为 0。
        System.out.println("位与运算符");
        System.out.println(num1);
        int num2 = 5 & 12;
        System.out.println(num2);
        // 参与运算的数字,低位对齐,高位不足的补零。
        // 如果对应的二进制位只要有一个为 1,那么结果就为 1;
        // 如果对应的二进制位都为 0,结果才为 0。
        System.out.println("位或运算符");
        int num3 = 11|7;
        System.out.println(num3);
        // 参与运算的数字,低位对齐,高位不足的补零.
        // 如果对应的二进制位相同(同时为 0 或同时为 1)时,结果为 0;
        // 如果对应的二进制位不相同,结果则为 1。
        System.out.println("位异或运算符");
        int num4 = 11^7;
        System.out.println(num4);
        //只对一个操作数进行运算,将操作数二进制中的 1 改为 0,0 改为 1。
        //对所有整数取反 = 本身的相反数 -1
        System.out.println("位取反运算符");
        int num5 = ~10;
        System.out.println(num5);
        //按二进制形式把所有的数字向左移动对应的位数,高位移出(舍弃),低位的空位补零。
        System.out.println("左位移运算符");
        int num6 = 11 << 1;//将整数 11 向左位移 1 位(相当于原来数的 2 倍)
        System.out.println(num6);
        //按二进制形式把所有的数字向右移动对应的位数,低位移出(舍弃),高位的空位补零。
        System.out.println("右位移运算符");
        int num7 = 11 >> 1;//将整数 11 向右位移 1 位(相当于原数整除 2 的结果)
        System.out.println(num7);
    }

在这里插入图片描述
在这里插入图片描述

  • 上述代码中位运算符运算过程

num1 运算过程
在这里插入图片描述

num2 运算过程在这里插入图片描述

num3 运算过程
在这里插入图片描述

num5 运算技巧
对所有整数取反 = 本身的相反数 -1

num4 运算过程
在这里插入图片描述

num6 运算过程
在这里插入图片描述

num7 运算过程
在这里插入图片描述

日期、随机数

public static void main(String[] args) {
        //日期时间、数学、随机数
        float x =1.35f , y =8.9f;
        // 四舍五入
        System.out.println(Math.round(x));
        System.out.println(Math.round(y));
        double d1 = 10.1;
        System.out.println(Math.ceil(d1));//向上取整
        double d2 = 22.8;
        System.out.println(Math.floor(d2));//向下取整

        System.out.println(Math.abs(-10));// 绝对值
        System.out.println(Math.random());

        Random rand = new Random();
        System.out.println(rand);
        System.out.println(rand.nextInt());//产生一个随机数
        System.out.println(rand.nextInt(33)+1);// [0,33)+1

        UUID uuid = UUID.randomUUID();//生成一个不会重复的(十六进制)随机序列
        System.out.println(uuid);

        Date date = new Date();// 创建一个时间实例
        System.out.println(date);

        Date date1 = new Date(2022-1900,2-1,18,16,30,00);
        System.out.println(date1);

        //获取当前系统时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(2022,2-1,18,16,30,00);
        Date date2 = calendar.getTime();
        System.out.println(date2);


        //通过DateFormat API进行日期的格式处理
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(date1));
    }

在这里插入图片描述

数组的常用方法

package com.muqi;

public class ArrayDemo {
    public static void main(String[] args){
        /*
            声明数组:数据类型[] 变量名;
            数组的长度在初始化之后无法改变,数组的下表(索引)从0开始,下标的有效区间[0,N-1]
         */
        int[] arr1 = {11,22,33,44,55};// 如何对数组进行初始化
        System.out.println("arr1数组:"+"["+arr1[0]+","+arr1[1]+","+arr1[2]+","+
                arr1[3]+","+arr1[4]+"]");

        int[] arr2 = new int[8];// 声明一个长度为8的数组,此方法初始化后,所有元素均为0
        System.out.println("arr2数组:"+"["+arr2[0]+","+arr2[1]+","+arr2[2]+","+
                arr2[3]+","+arr2[4]+","+arr2[5]+","+arr2[6]+","+arr2[7]+"]");

        int[] arr3 = new int[] {-10,0,10,20,30,40};
        System.out.println("arr3数组:"+"["+arr3[0]+","+arr3[1]+","+arr3[2]+","+
                arr3[3]+","+arr3[4]+","+arr3[5]+"]");
        System.out.println("arr3数组的长度为:"+arr3.length);//数组长度
        System.out.println("arr3数组的最后一个元素为:"+arr3[arr3.length-1]);//数组的最后一个元素

        String[] arr4 = {"张三","李四","王五"};
        System.out.println("arr4数组:"+"["+arr4[0]+","+arr4[1]+","+arr4[2]+"]");

    }

}

在这里插入图片描述

循环的常用方法

public static void main(String[] args) {
        String weekDate = "";
        Calendar calendar = Calendar.getInstance();  // 获取当前时间
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;  // 获取星期的第几日
        switch (week) {
            case 0:
                weekDate = "星期日";
                break;
            case 1:
                weekDate = "星期一";
                break;
            case 2:
                weekDate = "星期二";
                break;
            case 3:
                weekDate = "星期三";
                break;
            case 4:
                weekDate = "星期四";
                break;
            case 5:
                weekDate = "星期五";
                break;
            case 6:
                weekDate = "星期六";
                break;
        }
        System.out.println("今天是 " + weekDate);
    }

在这里插入图片描述

public static void main(String[] args) {
        System.out.println("请输入考试成绩:");
        Scanner input = new Scanner(System.in);
        int score = input.nextInt(); // 接收键盘输入数据
        if (score >= 90) { // 考试成绩>=90
            System.out.println("优秀");
        } else if (score >= 80) { // 90>考试成绩>=80
            System.out.println("良好");
        } else if (score >= 60) { // 80>考试成绩>=60
            System.out.println("中等");
        } else { // 考试成绩<60
        System.out.println("差");
    }
}

在这里插入图片描述

package com.muqi;

public class RoundDemo{
    public static void main(String[] args){
        int[] arr1 = {11,22,33,44,55};// 数组进行初始化
        System.out.println("arr1数组:"+"["+arr1[0]+","+arr1[1]+","+arr1[2]+","+
                arr1[3]+","+arr1[4]+"]");
        System.out.println("================   while循环   ================================");
        // while 循环,先判断,再循环
        int i = 0;// 定义下标
        final int N = arr1.length;// final 为常量关键字,此时 N 为常量
        while(i <= N-1){
            System.out.println(arr1[i]);
            i++; // i = i + 1  ;   i += 1
        }
        // do whlie 循环,先循环,再判断
                System.out.println("================   do while循环   ================================");
        int j = 0;
        do {
            System.out.println(arr1[j]);
            j += 1;
        }while (j <= N-1);
        // for(普通for循环,foreach循环)
                System.out.println("================   for循环   ================================");
        for (int a = 0 ; a < N-1 ; a++){
            System.out.println(arr1[a]);
        }
        System.out.println("================   foreach循环(迭代器循环,不用控制下标)   ================================");
        for(int b : arr1){
            System.out.println(b);
        }
    }
}

在这里插入图片描述

常见异常

  • 异常是程序执行过程中产生的非正常执行过程;
  • 程序中应该有异常处理的代码,保证程序在发生异常时能够继续执行,而不是立即终止;
  • Java程序中的异常主要有两种:Exception 和 Error。
  • 在编译器无法预知发生的异常称之为运行时异常(非检测异常)

在idea编译器中查询到 idea64.exe.vmoptions 文件
在这里插入图片描述

虚拟器内存最小为128MB,最大为750MB。

# custom IntelliJ IDEA VM options

-Xms128m
-Xmx750m
-XX:ReservedCodeCacheSize=240m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djdk.http.auth.tunneling.disabledSchemes=""
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-javaagent:G:\IntelliJ IDEA 2018.2.6\bin\JetbrainsCrack-3.1-release-enc.jar

java.lang.OutOfMemoryError (内存不足错误)

//创建long类型的数组,初始化内存为8字节 1024 * 1024 *  1024 = 8GB,会抛出异常,内存溢出。
    public static void main(String[] args){
        long[] arr1 = new long[1024*1024*1024];
    }
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at com.muqi.ExceptionDemo.main(ExceptionDemo.java:10)

java.lang.StackOverflowError ( 堆栈溢出错误)

//方法的递归调用,也会造成栈内存溢出
public class ExceptionDemo {
    public static void a() {
        System.out.println("执行a方法");
        a();
    }
    public static void main(String[] args) {
        a();
    }
}
Exception in thread "main" java.lang.StackOverflowError

java.lang.ArrayIndexOutOfBoundsException( 数组索引越界异常)

    public static void main(String[] args) {
        int[] arr1 = new int[5];
        System.out.println(arr1[-1]);
    }
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
	at com.muqi.ExceptionDemo.main(ExceptionDemo.java:23)

java.lang.StringIndexOutOfBoundsException (字符串索引越界异常)

    public static void main(String[] args) {
        String str1 = "muqi";
        System.out.println(str1.charAt(10));
    }
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10
	at java.lang.String.charAt(String.java:658)
	at com.muqi.ExceptionDemo.main(ExceptionDemo.java:39)

java.lang.NullPointerException(空指针异常)

    public static void main(String[] args) {
        String str2 = null;
        System.out.println(str2.equals(str2));
    }
Exception in thread "main" java.lang.NullPointerException
	at com.muqi.ExceptionDemo.main(ExceptionDemo.java:47)

java.lang.ArithmeticException: / by zero (算数异常中的除零异常)

public static void main(String[] args) {
        int a = 0, b = 10;
        int c = b / a;
    }
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.muqi.ExceptionDemo.main(ExceptionDemo.java:54)

编译器异常是一种可以在编译阶段预测到的异常。

Unhandled exception: java.io.FileNotFoundException(未处理异常:找不到文件异常)

在这里插入图片描述

Error:(15, 35) java: 未报告的异常错误java.io.FileNotFoundException; 必须对其进行捕获或声明以便抛出

无论文件名及路径是否正确都会抛出 Unhandled exception: java.io.FileNotFoundException ;必须对其进行捕获或声明以便抛出。

解决办法一:声明异常(未处理异常,谁调用谁处理这个异常)

    public static void m1() throws FileNotFoundException{
        String fileName = "student_info.txt";
        File file = new File(fileName);
        InputStream inputStream = new FileInputStream(file);
    }

解决办法二:捕获异常(处理异常)

public static void m2() {
        String fileName = "student_info.txt";
        File file = new File(fileName);
        try {
            InputStream inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

当主函数同时调用m1()和m2()时,由于m1()函数声明异常,m2()函数捕获异常,所以m1()函数报错,m2()函数正常。
在这里插入图片描述
此时,仍可以采用两种解决办法:声明异常和抛出异常。
声明异常
在这里插入图片描述
捕获异常
在这里插入图片描述

对比两种方法的处理结果

	public static void main(String[] args)throws FileNotFoundException {
        m1();
    }
    //声明异常
    public static void m1() throws FileNotFoundException{
        String fileName = "student_inf.txt";
        File file = new File(fileName);
        InputStream inputStream = new FileInputStream(file);
        System.out.println("结束");
    }
Exception in thread "main" java.io.FileNotFoundException: student_inf.txt (系统找不到指定的文件。)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at com.muqi.ExceptionDemo.m1(ExceptionDemo.java:23)
	at com.muqi.ExceptionDemo.main(ExceptionDemo.java:14)

声明异常处理的结果是,到异常的语句时,后面语句不再执行。

	public static void main(String[] args) {
        m2();
    }
    //捕获异常
    public static void m2() {
        String fileName = "student_inf.txt";
        File file = new File(fileName);
        try {
            InputStream inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("结束");
    }
结束
java.io.FileNotFoundException: student_inf.txt (系统找不到指定的文件。)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at com.muqi.ExceptionDemo.m2(ExceptionDemo.java:31)
	at com.muqi.ExceptionDemo.main(ExceptionDemo.java:14)

捕获异常处理的结果是,遇到异常把异常输出到控制台,后续语句继续执行。

手动产生并向外抛出一个异常

	public static void main(String[] args) {
        m2();
        throw new RuntimeException("。。。运行时异常。。。");
    }
    //捕获异常
    public static void m2() {
        String fileName = "student_inf.txt";
        File file = new File(fileName);
        try {//我们将可能产生异常的代码放在try{...}语句块中
            InputStream inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {//当程序发生异常后将会跳转到对应的catch(...){...}中执行
            e.printStackTrace();
        }finally {//无论前面程序发生什么,finally{...}语句块一定会执行一次。

        }
        System.out.println("结束");
    }
java.io.FileNotFoundException: student_inf.txt (系统找不到指定的文件。)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at com.muqi.ExceptionDemo.m2(ExceptionDemo.java:30)
	at com.muqi.ExceptionDemo.main(ExceptionDemo.java:15)
Exception in thread "main" java.lang.RuntimeException: 。。。运行时异常。。。
	at com.muqi.ExceptionDemo.main(ExceptionDemo.java:16)
结束

集合

public static void main(String[] args) {
        String[] oldNames = {"张三","李四","王五","赵六","刘七"};
        int N = oldNames.length;
        String[] newNames = new String[2 * N];
        for (int i = 0; i < N ;i++){
            newNames[i] = oldNames[i];
        }
        newNames[N++] = "孙八";
        newNames[N++] = "周九";
        newNames[N++] = "钱十";
        oldNames = newNames;
        for (int j = 0 ; j < N;j++){
            System.out.println(oldNames[j]);
        }
    }

在这里插入图片描述
很麻烦,不方便。

List集合

  • List list = new ArrayList<>();//基于数组的实现,底层封装了数组
  • List list = new LinkedList<>();//基于链表的实现,底层封装了链表
public static void main(String[] args) {
        String[] oldNames = {"张三","李四","王五","赵六","刘七"};
        List<String> list = new ArrayList<>();//基于数组的实现
        for (int i = 0; i<oldNames.length; i++){
            list.add(oldNames[i]);
        }
        System.out.println(list);//返回集合中所有元素

        list.add("孙八");//默认在集合末尾添加一个新元素
        list.add("周九");
        list.add("钱十");
        System.out.println(list);//返回集合中所有元素

        list.add(0,"郑一");//在指定索引位置插入元素
        System.out.println(list);//返回集合中所有元素

        list.set(5,"曹二");//替换指定索引位置的元素
        System.out.println(list);//返回集合中所有元素

        list.remove("李四");//删除指定元素
        System.out.println(list);//返回集合中所有元素

        list.remove(5);//删除指定下标的元素
        System.out.println(list);//返回集合中所有元素

        System.out.println(list.contains("李四"));//判断是否存在某一个元素
        System.out.println(list.contains("周九"));//判断是否存在某一个元素
        System.out.println("List集合的长度(当前保存元素的个数)为:" + list.size());
    }

在这里插入图片描述

public static void main(String[] args) {
        String[] oldNames = {"张三","李四","王五","赵六","刘七"};
        List<String> list = new LinkedList<>();//封装了链表的实现
        for (int i = 0; i<oldNames.length; i++){
            list.add(oldNames[i]);
        }
        System.out.println(list);//返回集合中所有元素

        list.add("孙八");//默认在集合末尾添加一个新元素
        list.add("周九");
        list.add("钱十");
        System.out.println(list);//返回集合中所有元素

        list.add(0,"郑一");//在指定索引位置插入元素
        System.out.println(list);//返回集合中所有元素

        list.set(5,"曹二");//替换指定索引位置的元素
        System.out.println(list);//返回集合中所有元素

        list.remove("李四");//删除指定元素
        System.out.println(list);//返回集合中所有元素

        list.remove(5);//删除指定下标的元素
        System.out.println(list);//返回集合中所有元素

        System.out.println(list.contains("李四"));//判断是否存在某一个元素
        System.out.println(list.contains("周九"));//判断是否存在某一个元素
        System.out.println("List集合的长度(当前保存元素的个数)为:" + list.size());
    }

在这里插入图片描述
两种实现方法十分相似。

例:

public static void main(String[] args) throws FileNotFoundException {
        File file = new File("student_info.txt");
        FileInputStream fileInputStream = new FileInputStream(file);//定义一个输入流
        Scanner scanner = new Scanner(fileInputStream);//封装了读取数据的一系列方法
        LinkedList<String> list = new LinkedList<>();
        while (scanner.hasNextLine()) {
            list.add(scanner.nextLine());//读取文件的每一行,添加到list集合中
        }
        for (String b : list) {
            System.out.println(b);
        }
        System.out.println("==============查找“王五”同学的信息===============");
        String studentName = "王五";
        for (String a : list) {
            String[] line = a.split(";");
            if (line[1].equals(studentName)){
                System.out.println("学号:"+line[0]);
                System.out.println("姓名:"+line[1]);
                System.out.println("成绩:"+line[2]);
                System.out.println("班级:"+line[3]);
            }
        }
        System.out.println("================三班的同学如下==================");
        String className= "三班";
        for (String x : list) {
            String[] line = x.split(";");
            if (line[3].equals(className)){
                System.out.println("学号:" + line[0]+"\t\t\t\t\t\t\t\t"+"姓名:" + line[1]);
            }
        }
    }

在这里插入图片描述

Map集合

  • Map集合使用键值对的方式来存储数据,分别有基于检索二叉树的TreeMap和基于和哈希表结构的HashMap
  • <key,value>
  • key不能重复,value是可以重复的
public static void main(String[] args) {
        //声明一个Map集合
        Map<String,String> map1 = new HashMap<>();//无序的,根据哈希值排序
        Map<String,Integer> map2 = new TreeMap<>();//有序的,默认中序遍历
        Scanner scanner = null;
        try {
            scanner = new Scanner(new FileInputStream("student_info.txt"));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] info = line.split(";");
                //在map中保存键值对
                map1.put(info[0],line);//学号作为key,这一行信息作为value
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println("====================所有学生信息如下==============");
        Collection<String> values = map1.values();
        for (String v:values) {
            System.out.println(v);
        }

        System.out.println("============第一种遍历map1=============");
        for(Map.Entry<String, String> entry : map1.entrySet()){//Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。
            System.out.println(entry.getKey()+"\t\t\t"+entry.getValue());
        }
        System.out.println("============第二种遍历map1=============");
        for (String key : map1.keySet()) {
            System.out.println(key + "\t\t\t" + map1.get(key));
        }

        scanner.close();

    }

在这里插入图片描述

public static void main(String[] args) {
        //声明一个Map集合
        Map<String,String> map1 = new HashMap<>();//无序的,根据哈希值排序
        Map<String,Integer> map2 = new TreeMap<>();//有序的,默认中序遍历
        Scanner scanner = null;
        try {
            scanner = new Scanner(new FileInputStream("student_info.txt"));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] info = line.split(";");
                //在map中保存键值对
                map1.put(info[0],line);//学号作为key,这一行信息作为value
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
       scanner.close();

        scanner = new Scanner(System.in);//读取控制台的输入值
        System.out.println("欢迎进入学生信息检索系统!");
        System.out.println("请输入学号:");
        String no = scanner.nextLine();
        if (map1.containsKey(no)){//判断Map集合中,是否存在某个Key
            System.out.println(map1.get(no));
        }else {
            System.out.println("查无此人!");
        }

        scanner.close();

    }

if判断也可以换成以下形式

		String v = map1.get(no);
        if (v!=null){//判断Map集合中,是否存在某个Key
            System.out.println(v);
        }else {
            System.out.println("查无此人!");
        }

在这里插入图片描述
在这里插入图片描述

Set集合

Set集合不能保存重复元素

  • HashSet
  • TreeSet
public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        set.add(90);
        set.add(80);
        set.add(100);
        set.add(70);
        set.add(60);
        System.out.println("set集合的大小:" + set.size());
        set.add(100);//添加重复的值,不会增加set集合的大小
        System.out.println("set集合的大小:" + set.size());

        //元素不是按照大小和添加顺序进行排序打印,而是通过元素的哈希值
        for (Integer x : set) {
            System.out.println(x);
        }

    }

在这里插入图片描述

public static void main(String[] args) {
//        Set<Integer> set = new HashSet<>();
        Set<Integer> set = new TreeSet<>();//检索二叉树,默认中序遍历
        set.add(90);
        set.add(80);
        set.add(100);
        set.add(70);
        set.add(60);
        System.out.println("set集合的大小:" + set.size());
        set.add(100);//添加重复的值,不会增加set集合的大小
        System.out.println("set集合的大小:" + set.size());

        //元素按照大小进行排序,
        for (Integer x : set) {
            System.out.println(x);
        }

    }

在这里插入图片描述

IO流

public class IODemo {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        //true参数的作用:使用在文件末尾追加的方式打开一个文件
        Writer w = new FileWriter("student_info.txt",true);
        System.out.println("请录入新学生信息:");
        System.out.println("学号:");
        Map<String,String> map = new HashMap<>();
        map.put("stu_no",scanner.nextLine());
        System.out.println("姓名:");
        map.put("stu_name",scanner.nextLine());
        System.out.println("分数:");
        map.put("stu_so",scanner.nextLine());
        System.out.println("班级:");
        map.put("stu_class",scanner.nextLine());

        PrintWriter printWriter = new PrintWriter(w);//带有类似打印功能的输出流
        printWriter.println();//另起一行
        printWriter.print(format(map));
        printWriter.flush();
        printWriter.close();
        scanner.close();
    }
    public static String format(Map<String,String> map) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(map.get("stu_no"));
        stringBuilder.append(";");
        stringBuilder.append(map.get("stu_name"));
        stringBuilder.append(";");
        stringBuilder.append(map.get("stu_so"));
        stringBuilder.append(";");
        stringBuilder.append(map.get("stu_class"));
        return stringBuilder.toString();
    }
}

在这里插入图片描述

Navicat

Mysql 版本查询
在这里插入图片描述
数据库字符集设置 :utf8mb4 支持中文。
在这里插入图片描述

MySQL工具类

package com.muqi;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

//编写一个连接MySQL数据库的工具类
public class DBUtil {
    public static final String DRIVER = "com.mysql.cj.jdbc.Driver";//数据库驱动类路径
    //数据库服务的统一资源定位
    public static final String URL = "jdbc:mysql://127.0.0.1:3306/db_shixun?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
    public static final String USERNAME = "root";//账户
    public static final String PASSWORD = "root";//密码

    static  {
        try {
            Class.forName(DRIVER);//加载数据库驱动,获取数据库连接前的必须步骤
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection openConnection() {//获取连接的方法
        try {
            return DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeConnertion(Connection conn) {//关闭连接的方法
        try {
            conn.close();//关闭连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

测试:

import java.sql.*;

//JDBC Java数据库连接技术,在Java程序中访问数据库
public class JDBCDemo {
    public static void main(String[] args) {
        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
        System.out.println(connection);
    }
}

测试结果:
在这里插入图片描述

public static void main(String[] args) throws SQLException {
//        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
//        System.out.println(connection);
        addStudent();
    }

    public static void addStudent() throws SQLException {
        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
        String sql = "insert into student_info value(2,'测试',77,'二班')";
        Statement statement = connection.createStatement();//创建一个statement实例,执行静态SQL
        int n = statement.executeUpdate(sql);//执行一个SQL (DML: insert、delete、update )
        if (n>0){
            System.out.println("学生信息添加成功");
        }
    }

在这里插入图片描述
在这里插入图片描述

public static void main(String[] args) throws SQLException {
//        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
//        System.out.println(connection);
        //addStudent();
        deleteStudent();
    }

    public static void addStudent() throws SQLException {
        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
        String sql = "insert into student_info value(2,'测试',77,'二班')";
        Statement statement = connection.createStatement();//创建一个statement实例,执行静态SQL
        int n = statement.executeUpdate(sql);//执行一个SQL (DML: insert、delete、update )

        if (n>0){
            System.out.println("学生信息添加成功");
        }
    }

    public static void deleteStudent() throws SQLException {
        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
        String sql = "delete from student_info where id='2'";
        Statement statement = connection.createStatement();//创建一个statement实例,执行静态SQL
        int n = statement.executeUpdate(sql);//执行一个SQL (DML: insert、delete、update )

        if (n>0){
            System.out.println("学生信息删除成功");
        }
    }

在这里插入图片描述

在这里插入图片描述

public static void main(String[] args) throws SQLException, IOException {
//        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
//        System.out.println(connection);
        //addStudent();
        //deleteStudent();
        batchAdd();
    }

    public static void batchAdd() throws IOException, SQLException {
        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
        String path = "student_info.txt";
        String sql = "insert into student_info values(?,?,?,?)";//预编译SQL
        PreparedStatement preparedStatement = connection.prepareStatement(sql);//得到一个预编译的执行语句

        Scanner scanner = new Scanner(new File(path));
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();//每一行数据都以一组学生信息
            String[] infos = line.split(";");
            preparedStatement.setInt(1, Integer.valueOf(infos[0]));
            preparedStatement.setString(2, infos[1]);
            preparedStatement.setInt(3, Integer.valueOf(infos[2]));
            preparedStatement.setString(4, infos[3]);
            preparedStatement.addBatch();//在执行语句中添加一个批处理

        }
        preparedStatement.executeBatch();//执行批处理操作
        System.out.println("批处理添加学生信息已完成");
    }
}

在这里插入图片描述
在这里插入图片描述

public static void main(String[] args) throws SQLException, IOException {
//        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
//        System.out.println(connection);
        //addStudent();
        //deleteStudent();
        //batchAdd();
        selectStudent();
    }

    public static void selectStudent() throws SQLException {
        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
        String sql = "select * from student_info where id=?";
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要查询的学生学号:");
        String id = scanner.nextLine();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,id);
        ResultSet resultSet = preparedStatement.executeQuery();//执行select语句
        while (resultSet.next()) {
            System.out.println("学号:" + resultSet.getString("ID"));
            System.out.println("姓名:" + resultSet.getString("NAME"));
            System.out.println("分数:" + resultSet.getString("SCORE"));
            System.out.println("班级:" + resultSet.getString("CLASS"));
        }
    }
}

在这里插入图片描述

public static void main(String[] args) throws SQLException, IOException {
//        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
//        System.out.println(connection);
        //addStudent();
        //deleteStudent();
        //batchAdd();
        //selectStudent();
        updateStudent();
    }

    public static void updateStudent() throws SQLException {
        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
        String sql = "update student_info set nam=?,score=?,class=? where id=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,"测试修改");
        preparedStatement.setInt(2,91);
        preparedStatement.setString(3,"四班");
        preparedStatement.setInt(4,8);
        int n = preparedStatement.executeUpdate();
        if (n > 0) {
            System.out.println("学生信息已修改!");
        }
    }
}

在这里插入图片描述

在这里插入图片描述


    public static void main(String[] args) throws SQLException, IOException {
//        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
//        System.out.println(connection);
        //addStudent();
        //deleteStudent();
        //batchAdd();
        //selectStudent();
        //updateStudent();
        selectByClass();
    }

    public static void selectByClass() throws SQLException {
        Connection connection = DBUtil.openConnection();//借助我们编写的工具类获取一个数据库连接
        String sql = "select * from student_info where class=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,"三班");
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            System.out.print("学号:" + resultSet.getString("ID") + ",");
            System.out.print("姓名:" + resultSet.getString("NAM") + ",");
            System.out.print("分数:" + resultSet.getString("SCORE") + ",");
            System.out.println("班级:" + resultSet.getString("CLASS") + ",");
        }
    }
}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值