java快速入门1

public class bobo2{

	public static void main(String[] args) {
		System.out.println("bobo is studying java");
	}


}

文件名和公共类名相同且大小写相同,

结束语句带;分号

先是类,类里面是函数

编写.java的源文件,然后用javac编译文件生成.class文件,使用java执行文件java bobo2.java

得到结果

键盘输入小练习:

import java.util.Scanner;

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

		System.out.println("mingzi");
		String name = scanner.next();

		System.out.println("age");
		int age = scanner.nextInt();


		System.out.println("salry");
		double sal = scanner.nextDouble();

		System.out.println("xinxi  ruxia:");
		System.out.println(name + '\t'  + age + '\n' + sal);

类型转换

public class ChangeChar{
	public static void main(String[] args) {
		String name = "123456";
		double name2 = Double.parseDouble(name);
		float name3 = Float.parseFloat(name);
		

		System.out.println(name2);
		System.out.println(name3);

}

	}

if  结构记得用{          括起来        }括起来,没有18要乖乖;

import java.util.Scanner;


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

		System.out.println("nide age");
		int age = scanner.nextInt();

		if (age > 18){
			System.out.println("age=" + "\t" + age + "chaoguo  18 bie huaihuai");

		}
			
			else{
				System.out.println("meiyou  18 ye yao    guaiguai");
			}
			

	}

}

是不是闰年

import java.util.Scanner;

public class If04{


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

		System.out.println("qingshuru   year");
		int year =scanner.nextInt();

		if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ){

			System.out.println(year + "shi  run nian");

		}
			else{
				System.out.println(year + "bubububububushi  run nian");
			}




	}
}

小写字母变大写,用CASE语句:

import java.util.Scanner;

public class Switch03{

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

		System.out.println("qing shuru yige zimu a----e   zidong zhuanhuan wei daxie");


		char zimu = scanner.next().charAt(0);

		switch(zimu){
			case 'a':
				System.out.println("A");
				break;
			case 'b':
				System.out.println("B");
			case 'c':
				System.out.println("C");
			case 'd':
				System.out.println("D");
			case 'e':
				System.out.println("E");
		}
	}
}

表达式数据类型要和case后一致,字符配字符,字符串配字符串:case子句里不能是变量

import java.util.Scanner;
public class Switch02{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("qing shuru nide mingzi");

        // char lu = scanner.next().charAt(0);
        String lu = scanner.next();

        switch(lu){
            case "lulu":
                System.out.println("lulu shi zuihaokan de nvhaizi");
            break;
            
        }
        }
            
    }


 

import java.util.Scanner;
public class Switch02{
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.println("qing shuru nide mingzi");

		// char lu = scanner.next().charAt(0);
		String lu = scanner.next();

		switch(lu){
			case "lulu":
				System.out.println("lulu shi zuihaokan de nvhaizi");
			break;
			
		}
		}
			
	}


switch及格吗

public class Switch04{
	public static void main(String[] args) {
		
		double fenshu = 88.5;

		switch((int)(fenshu/60)){
			case 0:
				System.out.println("bu  jige");
				break;

			case 1:
				System.out.println("jige  jige");
				break;
			default:
				System.out.println("cuo le");
				break;}

	}


}

For循环的入门

1打印一段话:

public class For1{


	public static void main(String[] args) {
		for (int i = 1;i <= 1052;i++)
			System.out.println("woshi  bobo" + i);
		for(int j = 1;j <= 822;j++)
			System.out.println("wowowoshi  bobobobo" + j);
	}
}

2打印一段话更新,变量自己输入

import java.util.Scanner;

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

		System.out.println("cong  duoshao qi");
		int i = scanner.nextInt();

		System.out.println("shuru  dayin dao duoshao weizhi");
		int n = scanner.nextInt();


		
		for(;i <= n;i++)
			System.out.println("i"+i);

	}
}

计数器,多少个满足条件

public class For6{


    public static void main(String[] args) {
        int count = 0;
        int i = 1;
        for (;i <= 100; i++){
            if(i % 9 == 0){       //注意作用域
                System.out.println(i);
                count++;
                }

        }
        System.out.println("duoshaoge  manzu tiaojian");
        System.out.println(count);
    }
        
}

public class For6{


	public static void main(String[] args) {
		int count = 0;
		int i = 1;
		for (;i <= 100; i++){
			if(i % 9 == 0){
				System.out.println(i);
				count++;
				}

		}
		System.out.println("duoshaoge  manzu tiaojian");
		System.out.println(count);
	}
		
}

计数器键盘输入和补充:从任意输入,到任意结束,统计总数,和总数的和

import java.util.Scanner;
	public class For6{


		public static void main(String[] args) {
			int count = 0;
			int sum = 0;
			Scanner scanner = new Scanner(System.in);
			System.out.println("cong duoshao qi ");
			int i = scanner.nextInt();
			System.out.println("cong duoshao jiesu");
			int n = scanner.nextInt();
			System.out.println("xiangyao  chuyiji");
			int j = scanner.nextInt();

			for (;i <= n; i++){
				if(i % j == 0){
					System.out.println(i);
					count++;
					sum += i;
					}

			}
			System.out.println("duoshaoge  manzu tiaojian");
			System.out.println(count);
			System.out.println("zonghe  shiduoshao ");
			System.out.println(sum);
			System.out.println("j= "+ j);
		}
			
	}

输出

0+5=5
1+4=5
2+3=5
3+2=5
4+1=5

public class For7jia{
	public static void main(String[] args) {
		int i = 0;
		int j = 5;
		for (;i <= 5;i++){
			System.out.println(i + "+" + (5-i) + "=5");
		}

}
}

先死后活:定义变量

public class For7jia{
	public static void main(String[] args) {
		int i = 0;
		int j = 5;
		int n = 1001;
		for (;i <= n;i++){
			System.out.println(i + "+" + (n-i) + "=" + n);
		}

}
}

while和for的基本使用格式:

public class For8{
	public static void main(String[] args) {
		int i = 0;
		

		for(; i <= 10;i++){
			System.out.println("nihao  bobo" + i);
		}
		int j = 0;
		while(j <= 15){
			j++;
			System.out.println("nihao shuaige  bobo" + j);
		}
		int q = 1;    
		while(q < 100){
			if (q % 3 ==0){
				System.out.println(q);
			}
			q++;
			
		}
		int e = 40;
		int f = 99;
		int g = 5;
		while(e < f){
			if (e % g == 0){
				System.out.println(e);
			}
			e++;
		}
	}
}

do while的用法:

public class DoWhile01{
	public static void main(String[] args) {
		int i = 1;
		do{
			System.out.println("bobo  haoshuai" + i);
			i++;
		}while(i <= 100);
	}
}

打印1--100的和:两个变量(两种方法)

public class DoWhile01{
	public static void main(String[] args) {
		int i = 1;
		int sum = 0;
		do{
			sum+=i;
			System.out.println(sum);
			i++;
		}while(i <= 100);
	}
}
public class if01{
	public static void main(String[] args) {
		int i = 1;
		int sum=0;
		for(;i <= 100;i++){
			sum=sum + i;
			System.out.println(sum);
		}
	}
}

统计个数和总数的和:

public class For2{
	public static void main(String[] args) {
		int i = 1;
		int n = 0;
		for(;i <= 200;i++){
			if(i % 5 == 0 && i % 3 !=0 ){
				System.out.println(i);
				n++;			
				}
				
		}
		System.out.println(n);
		
	}
}

个数的和:

public class For2{
	public static void main(String[] args) {
		int sum = 0;
		int i = 1;
		int n = 0;
		for(;i <= 200;i++){
			if(i % 5 == 0 && i % 3 !=0 ){
				System.out.println(i);
				n++;
				sum+= i;			
				}
				
		}
		System.out.println(n);
		System.out.println(sum);
	}
}

多重循环练习

import java.util.Scanner;
	public class PingJunFen{
		public static void main(String[] args) {
			Scanner scanner = new Scanner(System.in);
			int sum = 0;
			double pingjun;
			double jige;
			System.out.println("jegehaizi");
			// int n = scanner.nextInt();
			for (int j = 1;j <=5;j++){
				for(int i = 1;i <=5;i++){
					System.out.println("qing  shuru di"+ j +"geban" +'\t' + i + "ge  haizide fenshu");
					double score = scanner.nextDouble();
					System.out.println("di" +'\t' + i + "ge  haizide chengji" + score);
					if(score >= 60){
						System.out.println("di" +'\t' + i + "ge  haizide chengji" + score + "jige");
					}else{
						System.out.println("di" +'\t' + i + "ge  haizide chengji" + score + "bububujige");
					}
					sum += score;
					// n++;
					pingjun = sum/5;
					System.out.println("suoyouhaizide  zongfenwei" + '\t' + sum);
					System.out.println("suoyouhaizide  pingjunfenfenwei" + '\t' + pingjun);
				}
		}
	}
	}

生成1-100的随机数:

public class Break01{
	public static void main(String[] args) {
		for(int i = 0;i <= 10;i++){
			System.out.println((int)(Math.random() * 100) + 1);
		}
	}
}
	

字符串里的字符是一样的吗?字符串的内容比较:

import java.util.Scanner;
    public class Break03{
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);

            System.out.println("qing shuru yonghuming");
            String user = scanner.next();

            System.out.println("mima");
            String passwd = scanner.next();
            // int chance = 3;
            int i = 1;
            for(;i <= 10;i++){
                if("bobo".equals(user) && "666".equals(passwd)){
                    System.out.println("denglu  chenggong");
                    break;
                }

            }
        }
    }

import java.util.Scanner;
	public class Break03{
		public static void main(String[] args) {
			Scanner scanner = new Scanner(System.in);

			System.out.println("qing shuru yonghuming");
			String user = scanner.next();

			System.out.println("mima");
			String passwd = scanner.next();
			// int chance = 3;
			int i = 1;
			for(;i <= 10;i++){
				if("bobo".equals(user) && "666".equals(passwd)){
					System.out.println("denglu  chenggong");
					break;
				}

			}
		}
	}

过路口:+

public class LianXi1{
	public static void main(String[] args) {
		int i = 100000;
		int j = 0;
		while(true){
			if(i>50000){
				i*=0.95;
				System.out.println("haisheng +"+i);
				j++;
			}
			else if(i>=1000){
				System.out.println("meicijiao yiqian");
				i-=1000;
				System.out.println("haisheng +"+i);
				j++;
				System.out.println(j);
			}
			else {
				break;
			}

			
			
		}
	}
}
	

过路口2:

public class LianXi1{
	public static void main(String[] args) {
		double i = 100000;
		int  count = 0;
		while(true){
			if(i>50000){
				i*=0.95;
				count++;
			}else if(i>=1000){
				i-=1000;
				count++;
			}else break;
		}System.out.println(count);

			
			
		}
	}

	

水仙花数:

import java.util.Scanner;
	public class ShuiXianHua{
		public static void main(String[] args) {
			Scanner scanner = new Scanner(System.in);
			int n = scanner.nextInt();
			// int n = 153;
			int n1 = n / 100;
			int n2 = n % 100 / 10;
			int n3 = n % 10;

			if(n1*n1*n1+n2*n2*n2+n3*n3*n3 ==n){
				System.out.println(n+"shi shuixianhuashu");
			}else{
				System.out.println(n+"bububuuuuuushi shuixianhuashu");
			}
			
		}

	}

1-1/2+1/3-1/4:考察点:除法和浮点数的应用1.0/i

public class LianXi4{
	public static void main(String[] args) {
		double sum = 0;
		for(int i = 1;i <= 100;i++){
			if(i % 2 != 0){
				sum += 1.0/i;
			}else{
				sum-= 1.0/i;
			}
		}
		System.out.println(sum);
	}
}

1+(1+2)+(1+2+3):

public class LianXi4{
	public static void main(String[] args) {
		int sum = 0;
		for(int i = 1;i<=100;i++){
			for(int j = 1;j <= i;j++){
				sum+=j;

			}
		}
		System.out.print(sum);
	}
}

数组初体验:数组下标是从0编号的

public class Array02{
	public static void main(String[] args) {
		double [] hens = {3, 5, 1, 3.4, 2, 50};
		double total = 0;
		for(int i = 0;i < 6;i++){
			total+=hens[i];
			}
		System.out.println(total);
		System.out.println(total/6);
			// System.out.println("di"+ (i+1) +"ge yuansu  de zhi wei"+hens[i]);
		
	}
}

数组的基本使用:、

创建数组:char arrs[] = new char[26];

int arr1[]= {10,20,30};

int arr2[]= new int[arr1.length];

public class Array03{
	public static void main(String[] args) {
		double sum = 0;
		double hens[] = {1.0,3.0,6.0,5.0,8.0,9.0};
		int i = 0;
		for(;i < 6;i++){
			sum+= hens[i];
		}
		System.out.println(i);
		System.out.println(sum);
		System.out.println(sum/(i-1));
	}

}

数组名:数组名长度============数组名.length              hens.length 

        double sum = 0;
        double hens[] = {1.0,3.0,6.0,5.0,8.0,9.0};
        int i = 0;
        for(;i < hens.length;i++){
            sum+= hens[i];
        }

数组基础更新:数组名长度============数组名.length              hens.length  注意变量类型

public class Array04{
	public static void main(String[] args) {
		double sum = 0;
		double hens[] = {1.0, 3.0, 6.0, 5.0, 8.0, 9.0};
		int i =0;
		for(;i<hens.length;i++){
			sum += hens[i];
		}
		System.out.println(sum);
		System.out.println(sum/(hens.length-1));
	}
}

数组长度的使用和键盘更新:

scores[i] = scanner.nextDouble();

System.out.println("di i+1  ge  yuansu de zhi wei"+scores[i]);

import java.util.Scanner;
	public class Array05{
		public static void main(String[] args) {
			double scores[] = new double[6];
			Scanner scanner = new Scanner(System.in);
			for(int i = 0;i < scores.length;i++){
				System.out.println("qingshuru  di"+(i+1)+ "ge yusansu de zhi");
				scores[i] = scanner.nextDouble();
			}
			for(int i = 0; i< scores.length;i++){
				System.out.println("di" + (i+1) +  "ge  yuansu de zhi wei"+scores[i]);
			}
		}
	}

用数组打印A-----Z:

public class Array07{
	public static void main(String[] args) {
		char arrs[] = new char[26];
		for(int i=0;i<arrs.length;i++){
			arrs[i]=(char)('A'+i);
			System.out.println(arrs[i]);
		}
		for(int i=0;i<arrs.length;i++){
			System.out.print(arrs[i]);
		}		
	}
}

public class Array07{
	public static void main(String[] args) {
		char arrs[] = new char[26];

		for(int i=0;i<arrs.length;i++){
			arrs[i] =(char)('A'+ i);
			System.out.print(arrs[i]);
		}

	}
}

找出并打印出数组的最大值和下标:  int arr[]={4,-1,9,10,23,46,24};数组长度可以是变量了

public class Array07{
	public static void main(String[] args) {
		int arr[] = {4,-1,9,99};
		int max = arr[0];
		int maxIndex = 0;
		for(int i = 1;i < arr.length;i++){
			if(max<arr[i]){
				max = arr[i];
				maxIndex = i;
			}
		}
		System.out.println(max+"  "+maxIndex);
	}
}
public class Array09{
	public static void main(String[] args) {
		int arr[]={4,-1,9,10,23,46,9999,24,888};
		int i=0;
		for(;i<(arr.length-1);i++){
			// System.out.print(arr[i]+"  ");
			if(arr[i]>arr[i+1]){
				int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;	
                
			}

		}
		System.out.println("zuida shu de xia biao wei"+i);
		System.out.println(arr[arr.length-1]);

	}
}
	

把数组拷贝到新数组:创建新数组   让他有新地址空间,然后遍历

public class Array11{
	public static void main(String[] args) {
		int arr1[]= {10,20,30};

		int arr2[]= new int[arr1.length];

		for(int i = 0;i<arr1.length;i++){
			arr2[i] = arr1[i];
			arr2[0] = 50;
			System.out.print(arr2[i]);
		}


	}
}

数组翻转:(重学1)

public class FanZhuan{
	public static void main(String[] args) {
		int arr[]={11,22,33,44,55,66};
		//   arr[0],[1],[2],[3],[4],[5]; 
		//66  22 33 44 55 11
		//66  55 33 44 22 11
		//66  55 44 33 22 11        3ci =length/2
		// int arr2[]=new int[6];
		int temp = 0;
		for(int i = 0;i<(arr.length/2);i++){
			temp = arr[arr.length-1-i];

			arr[arr.length-1-i]=arr[i];
			arr[i] = temp;
		}
		for(int i = 0;i<(arr.length);i++){
			System.out.print(arr[i]+"\t");
		}
		

	}
}

数组翻转2:(重学)

public class FanZhuan{
	public static void main(String[] args) {
		int arr[]={11,22,33,44,55,66};
		int arr2[]=new int[arr.length];
		for(int i = arr.length-1,j=0;i>=0;i--,j++){
			arr2[j]=arr[i];
		}
		arr=arr2;
		for(int i = 0;i<arr.length;i++){
			System.out.print(arr[i]+"\t");
		}

	}
}

数据扩容:扩容数据赋值   arrNew[arrNew.length-1]=4;

public class KuoRong2{
	public static void main(String[] args) {
		int arr[]={1,2,3};

		int arrNew[]=new int[arr.length+1];
		for(int i=0;i<arr.length;i++){
			arrNew[i]=arr[i];
		}
		arrNew[arrNew.length-1]=4;
		arr = arrNew;

		for(int i=0;i<arr.length;i++){
			System.out.println(arr[i]);
		}
	}
}

扩容:

public class KuoRong{
	public static void main(String[] args) {
		int arr[]={1,2,3};
		int j=4;

		int arrs[]=new int[arr.length+1];

		for(int i =0;i<arr.length;i++){
			arrs[i]=arr[i];
		}
		arrs[arrs.length-1]=4;
		arr=arrs;
		
		for (int i =0; i <arr.length;i++){
			System.out.println(arr[i]);
		}
	}
}

数组翻转:两个交换,创建新数组,标记下标:

public class Fanzhuan{
	public static void main(String[] args) {
		int arr[]={11,22,33,44,55,66};
		int arrs[]=new int[arr.length];
		for(int i=0;i<arr.length;i++){
			arrs[i]=arr[arr.length-1-i];
		}
		arr=arrs;
		for(int i=0;i<arr.length;i++){
			System.out.print(arr[i]+" ");
		}
	}
}

maopao冒泡排序:

public class Bubble02{
    public static void main(String[] args) {
        int arr[]={11,33,22,44,55,23,69,56};
        for(int i = 0;i<arr.length-1;i++){
            for(int j = 0;j<arr.length-1-i;j++){
                if(arr[j]>arr[j+1]){
                    int temp =0;
                    temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                } 
            }
            System.out.print(arr[i]+"\t");
        }
    }
}

public class Bubble02{
	public static void main(String[] args) {
		int arr[]={11,33,22,44,55,23,69,56};
		for(int i = 0;i<arr.length-1;i++){
			for(int j = 0;j<arr.length-1-i;j++){
				if(arr[j]>arr[j+1]){
					int temp =0;
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				} 
			}
			System.out.print(arr[i]+"\t");
		}
	}
}

冒泡排序

public class Bubble06{
	public static void main(String[] args) {
		int arr[]={1,5,6,2,5,4,55,7,88,78,95,55,62,74};
		int i=0;
		for(;i<arr.length;i++){
			for(int j =0;j<arr.length-1-i;j++){
				if(arr[j]>arr[j+1]){
					int temp = 0;
					temp=arr[j];
					arr[j]=arr[j+1];
					arr[j+1]=temp;
		}
		}
		System.out.print(arr[i]+"\t");
		}

	}
}

冒泡排序:

    /**
     * 冒泡排序
     *      依次比较相邻的两个元素,如果前边的元素大于后边的元素则交换
     *      这样每次先排好的是最后一位
     *     3  1  6  8  0
     *     1  3  6  0  8   第0次比较:4次   从第一位开始到最后一位,排好了最后一位
     *     1  3  0  6  8   第1次比较:3次   从第一位开始到倒数第二位,排好了倒数第二位
     *     1  0  3  6  8   第2次比较:2次   ...
     *     0  1  3  6  8   第3次比较:1次   ...
     *     共比较4次
     *     完成!
     */
    @Test
    public void testBubbleSort(){
        // 准备待排序的数组
        int[] arr = {3,1,6,8,0};

        // 定义一个flag,用来记录上一轮是否有元素进行交换,
        // 如果上一轮没有元素进行交换,说明已经排序完成,停止排序(优化)
        boolean flag;

        for (int i = 0; i < arr.length - 1; i++) {//外层控制的是比较的轮数
            //每轮初始flag为true
            flag = true;
            for (int j = 0; j < arr.length - i - 1; j++) {//内层控制的是每轮比较的次数

                // 比较相邻两数的大小,如果前边的数大于后边的数,则交换位置
                if (arr[j] > arr[j+1]){

                    // 交换位置
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    //如果发生交换则flag改为false
                    flag = false;
                }
            }
            // 如果flag为true,则说明排序已经完成,结束循环
            if (flag){
                break;
            }
        }
        System.out.println(Arrays.toString(arr));//[0, 1, 3, 6, 8]
    }

冒泡冒泡(和我一样的):

public class MaoPao {
    public static void main(String[] args){
        int[] arrays = {4,2,3,1,5,8,9,6};
        msort(arrays);
        for(int i=0;i<arrays.length;i++){
            System.out.println(arrays[i]);
        }

    }
    public static  int[] msort(int[] arrays){
        
        for(int i=0;i<arrays.length;i++){
        	boolean flag = false;
            for(int j=0;j<arrays.length-1-i;j++){
                if(arrays[j]>arrays[j+1]){
                    int temp = arrays[j];
                    arrays[j]=arrays[j+1];
                    arrays[j+1]=temp;
                    flag=true;
                }
            }
            if(flag==false){
                break;
            }
        }
        return arrays;
    }
}

查找字符串在不在数组里:

import java.util.Scanner;	
	public class ShunXu{
		public static void main(String[] args) {
			String arr[] = {"baimao","heimao","jinmao","homgmao"};
			Scanner scanner = new Scanner(System.in);
			System.out.print("qingshuru  mouwang"+"\n");
			String findname = scanner.next();
			int index = -1;
			for(int i = 0;i<arr.length;i++){
				if(findname.equals(arr[i])){
					System.out.print(findname+"zai  shulie zhong"+"\t");
					System.out.print("xiabiao  wei"+i);
					index=i;
					break;
				}
				}
			if(index==-1){
					System.out.print("buzai  limian");

			}
		}
	}

二维数组基本输出:

public class ErWei{
	public static void main(String[] args) {

		//000000
		//001000
		//020300
		//000000
		int arr[][]={{0,0,0,0,0,0,},{0,0,1,0,0,0},{0,2,0,3,0,0},{0,0,0,0,0,0}};

		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.print("\n");
		}

	}
}

二维数组输出:

public class ErWei03{
	public static void main(String[] args) {
		int arr[][]={{0,0,0,0,0,0,0,0},{1,1,1,1,1,1,1,1},{1,2,3,4,5,6,7,8},{8,7,4,5,6,1,2,3}};

		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.print("\n");
		}
	}
}

二位数组:输出-----------------------------------arr[i][j]=j+1;输出为1//22//333//4444///55555///666666

数组开辟数据空间,二维数组开了,以为数组也得开:arr[i]=new int[i+1];

1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910

public class ErWei05{
	public static void main(String[] args) {
		int arr[][]=new int[10][];

		for(int i= 0;i<arr.length;i++){
			arr[i]=new int[i+1];
			for(int j =0;j<arr[i].length;j++){
				arr[i][j]=j+1;
			}
		}
		for(int i= 0;i<arr.length;i++){
			for(int j =0;j<arr[i].length;j++){
				System.out.print(arr[i][j]);
			}
			System.out.println();
		}	
	}
}

遍历二维数组并打印和:

public class ErWei07{
	public static void main(String[] args) {
		int arr[][]={{4,6},{1,4,5,7},{-2}};
		int sum=0;
		int i =0;
		for(;i<arr.length;i++){
			for(int j =0;j<arr[i].length;j++){
				sum+=arr[i][j];
				System.out.print(arr[i][j]+" ");
			}
		}
		System.out.println("\n"+sum);
	}
}

打印1--100的十个随机数:arr[i]=(int)(Math.random()*100)+1;

public class ZuoYe01{
	public static void main(String[] args) {
		int arr[]=new int[10];
		//(int)(Math.random()*100)+1
		for(int i=0;i<arr.length;i++){
			arr[i]=(int)(Math.random()*100)+1;
		}
		for(int i=0;i<arr.length;i++){
			System.out.print(arr[i]+"\t");
		}
	}
}

冒泡排序完整:注意哪里是length-1,,哪里是length

public class MaoPao2{
	public static void main(String[] args) {
		int arr[]={11,55,44,6,545,8,7,999,1021,452,265};

		for(int i =0;i<arr.length-1;i++){
			int temp =0;
			for(int j =0;j<arr.length-1-i;j++){
				if(arr[j]>arr[j+1]){
					temp=arr[j];
					arr[j]=arr[j+1];
					arr[j+1]=temp;
				}
			}
		}
		for(int i=0;i<arr.length;i++){
			for(int j =0;j<arr.length-1-i;j++){
			}
			System.out.print(arr[i]+"\t");
		}
		
	}
}

猫类是自定义的数据类型:猫类的入门

类入门:人类

public class RenLei{
	public static void main(String[] args) {
		Person p1=new Person();
		p1.age=25;
		p1.name="bobo";
		p1.sal=9600;
		p1.ispass=true;
		System.out.print(p1.age+"\t"+p1.name+"\t"+p1.sal+"\t"+p1.ispass);
	}
}

class Person{
	int age;
	String name;
	double sal;
	boolean ispass;
}
public class Proper{
	public static void main(String[] args) {
		Person person = new Person();
		person.age=5;
		person.name="bobobob";
		person.sal=100.11;
		person.ispass=true;
		System.out.println(person.age);
		System.out.println(person.name);
		System.out.println(person.sal);
		System.out.println(person.ispass);
	}
}
class Person{
	int age;
	String name;
	double sal;
	boolean ispass;
}

 猫类是自定义的数据类型:猫类的入门

定义一个猫类。定义他的属性和动作,在写main函数, 

猫等于新猫Cat cat1=new Cat();

猫的属性cat1.name...cat1.age...cat1.color...

class Cat{
	String name;
	int age;
	String color;
	public static void main(String[] args){
		Cat cat1=new Cat();
		cat1.name="xiao  bai";
		cat1.age=5;
		cat1.color="bai se";

		Cat cat2=new Cat();
		cat2.name="xiao hei";
		cat2.age=6;
		cat2.color="hei se";

		Cat cat3=new Cat();
		cat3.name="yuanyuan";
		cat3.age=7;
		cat3.color="huise";

		System.out.println(cat1.name+"\t"+cat1.age+"\t"+cat1.color);
		System.out.println(cat2.name+"\t"+cat2.age+"\t"+cat2.color);
		System.out.println(cat3.name+"\t"+cat3.age+"\t"+cat3.color);
	}
}

Car类

class Car2{
	String name;
	public static void main(String[] args){
		Car2 car3=new Car2();
		car3.name="bobo";
		System.out.print(car3.name);	
	}

}

猫类狗类在一起试试:

public class MaoLei2{
	public static void main(String[] args) {
		Mao mao1 = new Mao();
		mao1.age=5;
		mao1.name="baibai";
		mao1.weight=52;
		System.out.println(mao1.age+mao1.name+mao1.weight);

		Dog dog1=new Dog();
		dog1.age=6;
		dog1.name="gougou";
		dog1.weight=66;
		System.out.println(dog1.age+dog1.name+dog1.weight);

	}
}

class Mao{
	int age;
	String name;
	double weight;
}
class Dog{
	int age;
	String name;
	double weight;	
}

方法的初步 使用:

public class MaoLei3{
	public static void main(String[] args) {
		Mao mao1=new Mao();
		mao1.age=8;
		mao1.name="bobo";
		mao1.weight=56.2;

		mao1.speak();
	}
}
class Mao{
	int age;
	String name;
	double weight;
	public void speak(){
		System.out.println("woshi   haoren");
	}
}

成员方法的快速入门:注意DIAN      调用方法mao1.speak()

单参数和多参数使用

        int res = mao1.getSum(156,20);
        System.out.println(res);

    public void cal02(int n){
        int sum=0;
        for(int j=1;j<=n;j++){
            sum+=j;
        }
        System.out.println(sum);
    }

    public int getSum(int i,int j){
        int sum=i+j;
        return sum;
    }

public class Method{
	public static void main(String[] args) {
		Mao mao1=new Mao();
		mao1.age=8;
		mao1.name="bobo";
		mao1.weight=56.2;

		mao1.speak();
		mao1.cal01();
		mao1.cal02(5);
		mao1.cal02(666);

		int res = mao1.getSum(156,20);
		System.out.println(res);
	}
}
class Mao{
	int age;
	String name;
	double weight;
	public void speak(){
		System.out.println("woshi   haoren");
	}

	public void cal01(){
		int res=0;
		for(int i=1;i<=1000;i++){
			res+=i;
		}
		System.out.println(res);
	}

	public void cal02(int n){
		int sum=0;
		for(int j=1;j<=n;j++){
			sum+=j;
		}
		System.out.println(sum);
	}

	public int getSum(int i,int j){
		int sum=i+j;
		return sum;
	}
}

遍历数组多次:方法:

public class Method02{
	public static void main(String[] args) {
		int arr[][]={{0,0,1},{1,1,1},{1,1,3}};

		// for(int i=0;i<arr.length;i++){
		// 	for(int j=0;j<arr[i].length;j++){
		// 		System.out.print(arr[i][j]);
		// 	}
		// 	System.out.println();
		// }

		MyTools mytools = new MyTools();
		mytools.printArr(arr);
		mytools.printArr(arr);
		mytools.printArr(arr);

	}
}
class MyTools{
	public void printArr(int arr[][]){
		System.out.println("=================="+"\t");
		for(int i=0;i<arr.length;i++){
			for(int j=0;j<arr[i].length;j++){
				System.out.print(arr[i][j]+"   ");
			}
			System.out.println("\n");
		}		

	}
}

一个方法最多有一个返回值,如需返回多个用数组:

如果方法有要求返回数据类型,则方法体最后的执行语句中必须为renturn值

public class Method03{
	public static void main(String[] args) {
		AA aa = new AA();
		int[] resall=aa.getSum(8,4);
		System.out.println("he"+"\t"+resall[0]);
		System.out.println("cha"+"\t"+resall[1]);
	}
}
class AA{
	public int[] getSum(int n1,int n2){

		int res[]=new int[2];
		res[0]=n1+n2;
		res[1]=n1-n2;
		return res;
	}
}

基数偶数小练习(类):

public class Method04{
	public static void main(String[] args) {
		AA a = new AA();
		int jiou = a.aa(6);
	}
}
class AA{
	public int aa(int n){
		if(n%2==0){
			System.out.println("oushu");
		}
		else{
			System.out.println("jishu");
		}
		return n;
	}
}

简化:

public class Method04{
	public static void main(String[] args) {
		AA a = new AA();
		if(a.aa(5)){
			System.out.println("jishu");
		}else{
			System.out.println("oushu");
		}
	}
}
class AA{
	public boolean aa(int n){
		return n%2!=0;
	}
}

方法的使用------------------------数组的返回方法使用:

public class Method05{
	public static void main(String[] args) {
		Dog dog1 = new Dog();
		int arr[][]={{1,1,2},{3,3,6}};
		dog1.age=5;
		dog1.name="xiaobai";
		dog1.weight=55;
		System.out.println(dog1.age+dog1.name+dog1.weight);

		dog1.speak();
		dog1.qiuhe(20);
		dog1.qiuhe2(6,8);

		dog1.shuzu(arr);

		int res[]=dog1.jiajian(8,5);
		System.out.println("he"+"\t"+res[0]);

		System.out.println("cha"+"\t"+res[1]);
	}
}
class Dog{
	int age;
	String name;
	double weight;

	public void speak(){
		System.out.println("wang wang");
	}

	public int qiuhe(int n){
		int sum =0;
		for(int i = 0;i<=n;i++){
			sum+=i;
		}
		System.out.println(sum);
		return sum;
	}

	public int qiuhe2(int i,int j){
		int sum=i+j;
		System.out.println(sum);
		return sum;
	}

	public void shuzu(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]+" ");
			}
			System.out.println("\n");		
		}
	}

	public int[] jiajian(int i,int j){
		int res[]=new int[2];
		res[0]=i+j;
		res[1]=i-j;
		return res;
	}
	
}

数组传参是地址传参,会改变主方法的值

public class Method06{
	public static void main(String[] args) {
		int arr[]={1,6,5,45};

		B b = new B();
		b.test100(arr);
		for(int i=0;i<arr.length;i++){
			System.out.print(arr[i]+"\t");
		}
		System.out.println(" ");
	}
}
class B{
	public void test100(int arr[]){
		arr[0]=200;
		for(int i=0;i<arr.length;i++){
			System.out.print(arr[i]+"\t");
		}
		System.out.println(" ");
	}
}

对象克隆:

public class Method08{
	public static void main(String[] args) {
		Person p = new Person();
		p.name="li nan";
		p.age=5;
		p.weight=55;

		MyTools mytools=new MyTools();
		Person p2 = mytools.copyPerson(p);

		System.out.println(p.age+p.name+p.weight);
		System.out.print(p2.age+p2.name+p2.weight);

	}
}

class Person{
	String name;
	double weight;
	int age;
}

class MyTools{
	public Person copyPerson(Person p){
		Person p2 = new Person();
		p2.name=p.name;
		p2.age=p.age;
		p2.weight=p.weight;
		return p2;
	}
}

递归基础入门:

public class DiGui{
	public static void main(String[] args) {
		T t = new T();
		t.test(8);

	}
}
class T{
	public void test(int n){
		if(n>2){
			test(n-1);
		}
		System.out.println(n);
	}
}

递归和阶乘:

public class DiGui{
	public static void main(String[] args) {
		T t = new T();
		t.test(8);
		System.out.println("\n");

		int n1=t.factorial(8);
		System.out.println(n1);

	}
}
class T{
	public void test(int n){
		if(n>2){
			test(n-1);
		}
		System.out.println(n);
	}

	public int factorial(int n){
		if(n==1){
			return 1;
		}else{
			return factorial(n-1) * n;
		}

	}
}

递归阶乘:

public class DiGui02{
	public static void main(String[] args) {
		DiGui digui=new DiGui();
		
		System.out.print(digui.jiecheng(8));
	}
}

class DiGui{
	public int jiecheng(int n){
		if(n==1){
			return 1;
		}
		else{
			return jiecheng(n-1) * n;
		}
	}
}

斐波那契:

public class FeiBoNaQie{
	public static void main(String[] args) {
		T t = new T();
		int x = t.fei(8);
		System.out.println(x);
		return;
	}
}
class T{
	public int fei(int n){
		if(n>=1){
			if(n==1||n==2){
				return 1;
			}
			else{
				return fei(n-1)+fei(n-2);
			}
		}
		else{
			System.out.print("shuru dayudengyu  1  de shu");
			return 0;
		}
	}
}

老鼠出迷宫!!!(递归):

public class MiGong{
	public static void main(String[] args) {
		int map[][]=new int[8][7];
		for(int i=0;i<7;i++){
			map[0][i]=1;
			map[7][i]=1;	
		}
		for(int i=0;i<8;i++){
			map[i][0]=1;
			map[i][6]=1;
		}
		map[3][1]=1;
		map[3][2]=1;

		System.out.println("dangqian ditu");
		for(int i=0;i<map.length;i++){
			for(int j=0;j<map[i].length;j++){
				System.out.print(map[i][j]+"  ");
			}
			System.out.println();
		}

		T t1 = new T();
		t1.findWay(map,1,1);

		System.out.println("\n========zhaolu==========qingkuai=====");
		for(int i=0;i<map.length;i++){
			for(int j=0;j<map[i].length;j++){
				System.out.print(map[i][j]+"  ");
			}
			System.out.println();
		}		
	}
}
class T{
	//zhao  chumigong  lujing
	//zhao dao true
	//map  shi erwei shuzu  biaoshi migong
	//i,j  shi laoshu weizhi chushuzhiwei  (1,1)
	//tuichu  digui tiaojian   
	//0  keyizou   1zhangaiwu   2keyizou   3zouguo silu
	//map[6][5]=2;  tonglu
	//zhaolu  celve  xia..you..shang..zuo
	public boolean findWay(int map[][],int i,int j){
		if(map[6][5]==2){
			return true;
		}else{
			if(map[i][j]==0){
				//...
				map[i][j]=2;
				if(findWay(map,i+1,j)){
					return true;
				}else if(findWay(map,i,j+1)){
					return true;
				}else if(findWay(map,i-1,j)){
					return true;
				}else if(findWay(map,i,j-1)){
					return true;
				}else{
					map[i][j]=3;
					return false;
				}
				
			}else{
				return false;
			}
		}
	}
}

汉诺塔原理:

想要移动到C上,则需要先移动到B上,怎么移动到B上呢,借助C移动到B上;所以是a,c,b

                               然后移动到C上,怎么移动到c上呢?借助A移动到C上;所以是b,a,c

public class HanNuoTa{
	public static void main(String[] args) {
		Tower tower = new Tower();
		tower.move(4,'A','B','C');
	}
}
class Tower{
	//num  yidonggeshu   a,b,c   biaoshizhuzi
	public void move(int num,char a,char b,char c){
		if(num==1){
			System.out.println(a+"->"+c);
		}else{	
			move(num-1,a,c,b);
			System.out.println(a+"->"+c);
			move(num-1,b,a,c);	
					
			//yidong suoyoude pan dao  B,jiezhu  C
			//zuixiamiande  yidongdao C;
			//yidong suoyoude pan dao  c,jiezhu  a

		}
	}
}

汉诺塔代码(理解原理):

public class Tower02{
	public static void main(String[] args) {
		Tower tower = new Tower();
		tower.move(4,'A','B','C');
	}
}
class Tower{
	public void move(int num,char a,char b,char c){
		if(num==1){
			System.out.println(a+"-->"+c);
		}else{
			move(num-1,a,c,b);
			System.out.println(a+"-->"+c);
			move(num-1,b,a,c);
		}

	}
}

可变参数的使用;用可变参数求和:看成数组循环;可变参数的本质是数组

public class Canshu{
	public static void main(String[] args) {
		HspMethod hsp = new HspMethod();
		hsp.sum(1,100);
	}
}

class HspMethod{
	public int sum(int... nums){
		int res=0;
		for(int i=0;i<nums.length;i++){
			res+=nums[i];
		}
		System.out.println(res);
		// System.out.println(nums.length);
		return res;
	}
}

可变参数自己写的:

public class Canshu02{
	public static void main(String[] args) {
		CanShu canshu = new CanShu();
		canshu.sum(1,4,5);
	}
}
class CanShu{
	public void sum(int...nums){
		int sum=0;
		for(int i=0;i<nums.length;i++){
			sum+=nums[i];
		}
		System.out.println(sum);
	}
}

可变参数:名字和总分计算:

public class Canshu02{
	public static void main(String[] args) {
		HspMethod hsp = new HspMethod();
		hsp.showScore("tangbo",100,100);
		hsp.showScore("tangbo",100,100,100);
	}
}
class HspMethod{
	public void showScore(String name,double... nums){
		int sum=0;
		for(int i=0;i<nums.length;i++){
			sum+=nums[i];
		}
		System.out.println("mingzi shi"+name+"\t"+nums.length+"men  zongfen shi"+sum);
	}
}

构造器的使用和构造器的重载:快速入门:

public class Canshu02{
	public static void main(String[] args) {
		Person per = new Person("bobo",25);
	}
}
class Person{
	String name;
	int age;
	public Person(String pName,int pAge){
		name=pName;
		age=pAge;
		System.out.println(name+age);

	public Person(String pName){
		name=pName;
		System.out.println(name);	
	}
}

输出数组的最大值:

public class HomeWork01{
	public static void main(String[] args) {
		A01 a01 =new A01();
		double arr[]={5,5,6,4,5,7,3,3,9,3};
		a01.max(arr);
		System.out.println(a01.max(arr));
	}
}
class A01{
	public double max(double arr[]){
		double max1=arr[0];
		for(int i=0;i<arr.length;i++){
			if(max1<arr[i]){
				max1=arr[i];
			}

		}
		return max1;
	}
}

输出数组的最大值(自己敲的):

public class HomeWork001{
	public static void main(String[] args) {
		T t = new T();
		double arr[]={3,5,3,6,31,3,8,5};
		t.zuida(arr);
	}
}

class T{
	public double zuida(double arr[]){
		double max=arr[0];
		for(int i=0;i<arr.length;i++){
			if(max<arr[i]){
				max=arr[i];
			}
		}
		System.out.println(max);
		return max;
	}
}

或者这样写:本质都是看成数组;

public double max(double arr[]){

public double zuida(double... arr){

public class HomeWork001{
	public static void main(String[] args) {
		T t = new T();
		// double arr[]={3,5,3,6,31,3,8,5};
		t.zuida(3,5,3,6,31,3,8,5);
	}
}

class T{
	public double zuida(double... arr){
		double max=arr[0];
		for(int i=0;i<arr.length;i++){
			if(max<arr[i]){
				max=arr[i];
			}
		}
		System.out.println(max);
		return max;
	}
}

代码优化:

class T{
    public double zuida(double... arr){
        if(arr != null && arr.length>0){
            double max=arr[0];
            for(int i=0;i<arr.length;i++){
                if(max<arr[i]){
                    max=arr[i];
                }
            }
            System.out.println(max);
            return max;
        }
        else{
            return 0.0;
        }
    }
}

public class HomeWork001{
	public static void main(String[] args) {
		T t = new T();
		// double arr[]={3,5,3,6,31,3,8,5};
		t.zuida(3,5,3,6,31,3,8,5);
	}
}
class T{
	public double zuida(double... arr){
		if(arr != null && arr.length>0){
			double max=arr[0];
			for(int i=0;i<arr.length;i++){
				if(max<arr[i]){
					max=arr[i];
				}
			}
			System.out.println(max);
			return max;
		}
		else{
			return 0.0;
		}
	}
}

判断字符串是否在某一个数组中:

public class HomeWork02{
	public static void main(String[] args) {
		String strs[]={"jack","tom","mary","milan"};
		A02 a02 = new A02();
		int index =a02.find("jack",strs);
		System.out.print("zhaodao le  index="+index);
	}
}
class A02{
	public int find(String findstr,String strs[]){
		for(int i=0;i<strs.length;i++){
			if(findstr.equals(strs[i])){
				return i;
			}
		}
		return -1;
	}
}

更新书的价格:大于一百五的改成100,大于100小于150的改成100;

public class Change{
	public static void main(String[] args) {
		Book book = new Book("jiaohu",156);
		book.info();
		book.updatePrice();
		book.info();
	}
}
class Book{

	String name;
	double price;

	public Book(String name,double price){
		this.name=name;
		this.price=price;
	}
	public void updatePrice(){
		if(this.price>150){
			this.price=150;
		}
		else if(this.price>100 && this.price<150){
			this.price=100;
		}
		else{

		}
	}

	public void info(){
		System.out.print("shuming="+this.name+"dangqian  jiage="+this.price);
	}
}

将原数组复制到新数组中:

public class HomeWork04{
	public static void main(String[] args) {
		ShuZu shuzu = new ShuZu();
		int arr[]={1,3,1,5,7,1,8};
		int nums[]=shuzu.copyArr(arr);
		for(int i=0;i<nums.length;i++){
			System.out.print(nums[i]+"\t");
		}
	}
}

class ShuZu{
	public int[] copyArr(int arr[]){
		int nums[]=new int[arr.length];
		for(int i=0;i<arr.length;i++){
			nums[i]=arr[i];
		}
		return nums;
	}
}

求圆的周长和面积:构造器:

public class HomeWork04{
	public static void main(String[] args) {
		Yuan yuan=new Yuan(2);
		yuan.area();
		System.out.println("mianji"+yuan.area());
		System.out.println("zhouchang"+yuan.zhouchang());
	}
}
class Yuan{
	double r;
	//zhouchang===2   pai  r
	//mianji   pai  r*r
	// double mianji;
	// double zhouchang;
	public Yuan(double r){
		this.r=r;
	}

	public double area(){
		return Math.PI*r*r;
	}

	public double zhouchang(){
		return 2*Math.PI*r;
	}

}

加减乘除:构造器:

public class HomeWork06{
	public static void main(String[] args) {
		Cale cale = new Cale(2,4);
		// ;
		// cale.minus();
		// cale.mul();
		// cale.div();
		System.out.println(cale.sum());
		System.out.println(cale.minus());
		System.out.println(cale.mul());
		System.out.println(cale.div());
	}
}
class Cale{
	double n1;
	double n2;
	//gouzao qi
	public Cale(double n1,double n2){
		this.n1=n1;
		this.n2=n2;
	}

	public double sum(){
		return n1+n2;
	}
	public double minus(){
		return n1-n2;
	}
	public double mul(){
		return n1*n2;
	}
	public Double div(){
		//n1!=0&&
		if(n2!=0){
			return n1/n2;
		}else{
			return null;
		}
	}
}

通过IDEA写的冒泡:

public class TestTemplate {
    public static void main(String[] args) {

        System.out.println();
        int arr[]={1,5,1,5,6,4,55,84,55};
        int temp=0;
        for (int i = 0; i <arr.length-1; i++) {
            for (int j = 0; j <arr.length-1-i ; j++) {
                if(arr[j]>arr[j+1]){
                    temp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }

        }
        for (int i = 0; i <arr.length; i++) {
            System.out.print(arr[i]+"\t");

        }
    }
}

通过IDEA写的冒泡加构造器+方法

import java.util.Scanner;


public class ArrayTest {
    public static void main(String[] args) {

        Scanner myScanner = new Scanner(System.in);
        MyTools mt = new MyTools();
        int arr[] = {-1, 10, 8, 0, 34};
        mt.bubble(arr);
        //输出排序后的排序,数组是引用传递
        System.out.println("===排序后的数组是");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }

    }
}
class Person{
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}


class MyTools {
    public void bubble(int arr[]) {
        //冒泡排序
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

封装的快速入门:设置年纪限制,名字长度限制,快捷键Alt+Insert设置校验逻辑

package com.hspedu.encap;

public class Encapsulation01 {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("伯jack");
        person.setAge(30);
        person.setSalary(30000);
        System.out.println(person.info());
    }
}

class Person {
    public String name;
    private int age;
    private double salary;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if(name.length()>=2&&name.length()<=6){
            this.name = name;
        }else{
            System.out.println("长度不对,名字的长度应该在2---6位字符,默认无名");
        }
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age>=1&&age<=120){
            this.age = age;
        }else{
            System.out.println("年龄应该在1--120之间,默认给18岁哟");
            this.age=18;
        }

    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String info() {
        return "信息为" + name + "age=" + age + "sal=" + salary;
    }
}

改进====在构造器中设置限制,防破坏逻辑:

package com.hspedu.encap;

public class Encapsulation01 {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("伯jack");
        person.setAge(30);
        person.setSalary(30000);
        System.out.println(person.info());

        Person smith = new Person("smith", 5555, 50000);
        System.out.println("=====smith的信息为======");
        System.out.println(smith.info());

    }
}

class Person {
    public String name;
    private int age;
    private double salary;

    //构造器alt+insert
    public Person() {
    }

    public Person(String name, int age, double salary) {
//        this.name = name;
//        this.age = age;
//        this.salary = salary;
        //可以将set方法写入构造器中,仍然可以验证,防破解
        setName(name);
        setAge(age);
        setSalary(salary);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if(name.length()>=2&&name.length()<=6){
            this.name = name;
        }else{
            System.out.println("长度不对,名字的长度应该在2---6位字符,默认无名");
        }
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age>=1&&age<=120){
            this.age = age;
        }else{
            System.out.println("年龄应该在1--120之间,默认给18岁哟");
            this.age=18;
        }

    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String info() {
        return "信息为" + name + "age=" + age + "sal=" + salary;
    }
}

账号密码余额设置范围:

package com.hspedu.encap;

public class Account {
    public static void main(String[] args) {
        Accounts1 accounts1 = new Accounts1();
        accounts1.setName("jack");
        accounts1.setBalance(60);
        accounts1.setPwd("666666");

        accounts1.showInfo();

    }
}

class Accounts1 {
    private String name;
    private double balance;
    private String pwd;

    public Accounts1() {
    }

    public Accounts1(String name, double balance, String pwd) {
        this.setName(name);
        this.setBalance(balance);
        this.setPwd(pwd);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name.length() > 1 && name.length() <= 4) {
            this.name = name;
        } else {
            System.out.println("姓名在2--4位之间,默认为默认用户");
            this.name = "默认用户";
        }
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        if (balance > 20) {
            this.balance = balance;
        } else {
            System.out.println("余额不满足要求,必须大于20");
        }
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        if (pwd.length() == 6) {
            this.pwd = pwd;
        } else {
            System.out.println("密码必须是六位");
        }
    }

    public void showInfo() {
        System.out.println(name + "\t" + balance + "\t" + pwd + "\t");
    }
}

调用父类的say方法,使用方法的重构时候要注意使用super         super.say()

public String say(){
    return super.say() +"我的"+id+"今年"+score+"分";
}

重写equals方法,判断两个___对象_____是否相同:

        if(obj instanceof Person02){//类型判断同一类才比较
            Person02 p2 = (Person02)obj;   //向下继承
            return this.name==p2.name&&this.age==p2.age&&this.scores==p2.scores;
        }

package com.hspedu.equals;

public class Equals02 {
    public static void main(String[] args) {
        Person02 person02 = new Person02("bobo",25,98);
        Person02 person03 = new Person02("bobo",25,98);
        System.out.println(person02.equals(person03));
    }
}
class Person02{
    private String name;
    private int age;
    private double scores;

    public boolean equals(Object obj){
        if(this==obj){
            return true;
        }
        if(obj instanceof Person02){
            Person02 p2 = (Person02)obj;
            return this.name==p2.name&&this.age==p2.age&&this.scores==p2.scores;
        }
        return false;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getScores() {
        return scores;
    }

    public void setScores(double scores) {
        this.scores = scores;
    }

    public Person02() {
    }

    public Person02(String name, int age, double scores) {
        this.name = name;
        this.age = age;
        this.scores = scores;
    }
}

数组中按特定属性大小排序:age             if(person[j].getAge()<person[j+1].getAge()){

也可以按照名字长度排序:(机智)

if(person[j].getName().length()<person[j+1].getName().length()){
package com.hspedu.exercise;

public class Exercise01 {
    public static void main(String[] args) {
        Person person[]= new Person[3];
        person [0] = new Person("bobo", 25, "软件测试");
        person [1]  = new Person("小明", 20, "保洁员");
        person [2]  = new Person("校长", 50, "校长");

        for (int i = 0; i < person.length; i++) {
            System.out.println("排序qian的效果");
            System.out.println(person[i]);
        }
        for (int i = 0; i < person.length; i++) {
            for (int j = 0; j < person.length-i-1; j++) {
                if(person[j].getAge()<person[j+1].getAge()){
                    Person temp=null;
                    temp=person[j];
                    person[j]=person[j+1];
                    person[j+1]=temp;
                }

            }
        }
        System.out.println("排序后的效果");
        for (int i = 0; i < person.length; i++) {
            System.out.println(person[i]);
        }
    }
}
class Person{
    private String name;
    private int age;
    private String job;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public Person() {
    }

    public Person(String name, int age, String job) {
        this.name = name;
        this.age = age;
        this.job = job;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", job='" + job + '\'' +
                '}';
    }
}

排序结果:

排序qian的效果
Person{name='bobo', age=25, job='软件测试'}
排序qian的效果
Person{name='小明', age=20, job='保洁员'}
排序qian的效果
Person{name='校长', age=50, job='校长'}
排序后的效果
Person{name='校长', age=50, job='校长'}
Person{name='bobo', age=25, job='软件测试'}
Person{name='小明', age=20, job='保洁员'}

自己重新敲了一遍,按职业名字长度排序:

package com.hspedu.exercise03;

public class Exercise03 {
    public static void main(String[] args) {
        Person[] persons = new Person[3];
        persons[0]=new Person("bobo",25,"软件测试");
        persons[1]=new Person("jack",26,"软件测试工程师");
        persons[2]=new Person("tom",20,"小白");

        for (int i = 0; i < persons.length; i++) {
            System.out.println(persons[i]);
        }

        for (int i = 0; i < persons.length-1; i++) {
            for (int j = 0; j < persons.length-1-i; j++) {
                Person temp=null;
                if(persons[j].getJob().length()>persons[j+1].getJob().length()){
                    temp=persons[j];
                    persons[j]=persons[j+1];
                    persons[j+1]=temp;
                }
            }
        }
        System.out.println("排序后");
        for (int i = 0; i < persons.length; i++) {
            System.out.println(persons[i]);
        }

    }
}
class Person{
    private String name;
    private int age;
    private String job;

    public Person() {
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", job='" + job + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public Person(String name, int age, String job) {
        this.name = name;
        this.age = age;
        this.job = job;
    }
}

打印出教师职称和对应职称工资(方法重写):

package com.hspedu.Exerxise04;

public class Exercise04 {
    public static void main(String[] args) {
        Professor professor = new Professor("bobo",25,"教授",10000);
        FuProfessor teacher02 = new FuProfessor("xiaoming",24,"fu教授",10000);
        PuTongTeacher teacher03 = new PuTongTeacher("putong",20,"putong",10000);

        professor.introduce();
        teacher02.introduce();
        teacher03.introduce();
    }
}

class teacher{
    private String name;
    private int age;
    private String post;
    private double salary;

    public void introduce(){
        System.out.println("教师的基本信息为");
        System.out.println(getName()+getAge()+getPost()+getSalary());
    }

    @Override
    public String toString() {
        return "teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", post='" + post + '\'' +
                ", salary=" + salary +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPost() {
        return post;
    }

    public void setPost(String post) {
        this.post = post;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public teacher() {
    }

    public teacher(String name, int age, String post, double salary) {
        this.name = name;
        this.age = age;
        this.post = post;
        this.salary = salary;
    }
}
class Professor extends teacher{
    public Professor() {
    }

    public Professor(String name, int age, String post, double salary) {
        super(name, age, post, salary);
    }

    @Override
    public double getSalary() {
        return super.getSalary()*1.3;

    }
    @Override
    public void introduce() {
        super.introduce();
    }
}

class FuProfessor extends teacher{
    public FuProfessor() {
    }

    public FuProfessor(String name, int age, String post, double salary) {
        super(name, age, post, salary);
    }

    @Override
    public double getSalary() {
        return super.getSalary()*1.2;
    }

    @Override
    public void introduce() {
        System.out.println(getName()+getAge()+getPost()+getSalary());
    }
}

class PuTongTeacher extends teacher{
    public PuTongTeacher() {
    }

    public PuTongTeacher(String name, int age, String post, double salary) {
        super(name, age, post, salary);
    }

    @Override
    public double getSalary() {
        return super.getSalary()*1.1;
    }
    @Override
    public void introduce() {
        super.introduce();
    }
}

d代码块的快速入门--------

重复动作放入块中:(普通代码块)

    {
        System.out.println("放广告先");
    }

普通代码块每次都执行,静态代码块只执行一次:

static {
    System.out.println("放广告先");
}
package com.hspedu.codeblock;

public class CodeBlock {
    public static void main(String[] args) {
        Movie movie = new Movie("你好,李焕英");
        Movie movie3 = new Movie("你好,李焕英",110);
        Movie movie2 = new Movie("你好,李焕英",100,"唐波");

    }
}
class Movie{
    private String name;
    private double price;
    private String director;

    {
        System.out.println("放广告先");
    }

    public Movie(String name) {
        this.name = name;
        System.out.println("第一个电影");
    }

    public Movie(String name, double price) {
        this.name = name;
        this.price = price;
        System.out.println("第二个电影");
    }

    public Movie(String name, double price, String director) {
        this.name = name;
        this.price = price;
        this.director = director;
        System.out.println("第三个电影"+this.name);
    }

}

t代码块继承的顺序:super()是关键,然后执行本类

package com.hspedu.codeblock;

public class CodeBlock03 {
    public static void main(String[] args) {
        BBB bbb = new BBB();
    }
}
class AAA{
    public AAA() {
        super();
        System.out.println("AA的无参构造器被调用...");
    }
}
class BBB extends AAA{
    {
        System.out.println("BB的普通代码块被调用...");
    }
    public BBB() {
        super();//1.super    2.调用本类的普通代码块
        System.out.println("BB的无参构造器被调用...");
    }
}

s谁是你的女朋友(单例模式饿汉式):

步骤:

1.将构造器私有化,防止用new创建

生成构造器,然后public改成private

private GirlFriend(String name) {
    this.name = name;
}

2.在类的内部直接创建静态对象

外面不能new,在本类里可以new

private  static GirlFriend girlFriend=new GirlFriend("小红");

3.提供一个公共的static方法,返回gf对象

定义一个公共静态方法,返回值是你原来的私有对象,这样别人调用这个方法,就看见你女朋友了

public static GirlFriend getInstance(){
    return girlFriend;
}

4.可以给一个tostring方法。获得你女朋友的名字

5.怎么调用:用类名.方法调用  -------------------------GirlFriend.getInstance();

public static void main(String[] args) {
    GirlFriend instance = GirlFriend.getInstance();
    System.out.println(instance);
}
package com.hspedu.single_;

public class SingleTol01 {
//    GirlFriend girlFriend=new GirlFriend("小红");
    public static void main(String[] args) {
        GirlFriend instance = GirlFriend.getInstance();
        System.out.println(instance);
    }
}
class GirlFriend{

    private String name;

    private  static GirlFriend girlFriend=new GirlFriend("徐磊");

    private GirlFriend(String name) {
        this.name = name;
    }
    public static GirlFriend getInstance(){
        return girlFriend;
    }

    @Override
    public String toString() {
        return "GirlFriend{" +
                "name='" + name + '\'' +
                '}';
    }
}

(只让你养一只猫)懒汉式单例设计模式:

1.构造器私有化

2.定义static静态对象

3定义一个public方法用来返回cat

4,只有在用户使用getinstance时候才返回cat对象;

package com.hspedu.single_;

public class SingleTol02 {
    public static void main(String[] args) {
        System.out.println(Cat.n1);
        Cat instance = Cat.getInstance();
        System.out.println(instance);

        Cat instance2 = Cat.getInstance();
        System.out.println(instance2);

        System.out.println(instance==instance2);
    }
}
//只能养一只猫
class Cat{
    private String name;
    public static int n1=999;
    private static Cat cat;

    private Cat(String name) {
        this.name = name;
    }
    public static Cat getInstance(){
        if(cat==null){
            cat=new Cat("小可爱");
        }
        return cat;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                '}';
    }
}

抽象类模板设计简单入门:

1,定义抽象类

2,创建抽象方法

3,创建方法,你要做的事情,比如计算时间差

4,创建新类继承抽象类,重写抽象方法

5,创建Test类,调用方法

package com.hspedu.abstract03;

abstract public  class Abstract03 {
    public abstract void job();

    public void Cal(){
        long start=System.currentTimeMillis();
        job();
        long end=System.currentTimeMillis();
        System.out.println(end-start);
    }
}
package com.hspedu.abstract03;

public class BBB extends Abstract03{
    @Override
    public void job() {
        int num=0;
        for (int i = 0; i < 10000; i++) {
            num+=i;
        }
        System.out.println(num);
    }
}
package com.hspedu.abstract03;

public class Test {
    public static void main(String[] args) {
        BBB bbb = new BBB();
        bbb.Cal();
    }
}

匿名内部类入门:

package com.hspedu.interface_class;

public class AnonyClass {
    public static void main(String[] args) {
        IA tiger=new IA(){
            @Override
            public void cry() {
                System.out.println("老虎在叫唤...");
            }
        };
        tiger.cry();
    }
}
interface IA{
    public void cry();
}

类的匿名内部类:

package com.hspedu.interface_class;

public class Anonymous {
    public static void main(String[] args) {
        IA2 tt=new IA2(){
            @Override
            public void cry2() {
                System.out.println("tt在哭了");
            }
        };
        tt.cry2();
        System.out.println(tt.getClass());

        Father jack = new Father("jack"){
            @Override
            public void test() {
                System.out.println("我在重写匿名内部类的方法");
            }
        };
        System.out.println(jack.getClass());
        jack.test();
    }
}
interface IA2{
    public void cry2();
}

class Father{
    public Father(String name) {
    }
    public void test(){

    }
}

匿名内部类细节:

package com.hspedu.interface_class;

public class AnonymousInnerClassDetail {
    public static void main(String[] args) {
        Outer05 outer05 = new Outer05();
        outer05.f1();
    }
}
class Outer05 {
    private int n1 = 99;


    void f1() {
        Person p = new Person() {
            @Override
            public void hi() {
                System.out.println("匿名内部类重写了hi方法");
            }
        };
        p.hi();

        new Person() {
            @Override
            public void hi() {
                System.out.println("222222222重写了hi方法");
            }
        }.ok("波波");
    }

    class Person {
        public void hi() {
            System.out.println("Person hi()");
        }
        public void ok(String name){
            System.out.println(name);
        }
    }
}

自定义枚举类:

package com.hspedu.enumeration01;

public class Enumeration01 {
    public static void main(String[] args) {
        System.out.println(Season.autumn);
    }
}

class Season {
    private String name;
    private String desc;

    public final static Season spring = new Season("春天", "春天花开");
    public final static Season winter = new Season("冬天", "白雪皑皑");
    public final static Season summer = new Season("夏天", "夏天游泳");
    public final static Season autumn = new Season("秋天", "丰收季节");


    private Season(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }

    @Override
    public String toString() {
        return "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

enum枚举类1:

枚举的初步使用:

步骤:1.使用关键字enum代替class

2.enum Season {
    SPRING("春天","温暖"),SUMMER("夏天","闷热");

}

3.多个常量,逗号间隔

package com.hspedu.enumeration01;

public class Enumeration01 {
    public static void main(String[] args) {
        System.out.println(Season.SPRING);
        System.out.println(Season.SUMMER);
    }
}

enum Season {
    SPRING("春天","温暖"),SUMMER("夏天","闷热");
    private String name;
    private String desc;

    private Season(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }

    @Override
    public String toString() {
        return "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

用枚举打印周一到周天:

增强FOR循环:

package com.hspedu.enumeration01;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Enum2 {
    public static void main(String[] args) {
        Week[] values = Week.values();
        for(Week week:values){
            System.out.println(week);
        }
    }
}
enum Week{
    MONDAY("星期一"),TUESDAY("星期ER");
    private String name;

    Week(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

自己有敲了一遍:

package com.hspedu.override_;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Enum04 {
    public static void main(String[] args) {
        Week04[] week04s=Week04.values();
        Week04 m1 = Week04.M1;
        Week04 m2 = Week04.M2;
        System.out.println(m1);
        System.out.println(m2);
        for(Week04 week04:week04s){
            System.out.println(week04);
        }

    }
}
enum Week04{
    M1("星期一"),M2("星期二")
    ;
    private String name;

    Week04(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Week04{" +
                "name='" + name + '\'' +
                '}';
    }

    public void setName(String name) {
        this.name = name;
    }
}

s使用匿名内部类实现计算方法:加减乘除都行;

//匿名内部类的特征是可以作为参数传递

package com.hspedu.override_;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HomeWork04 {
    public static void main(String[] args) {
        CellPhone cellPhone = new CellPhone();
        //匿名内部类的特征是可以作为参数传递
        cellPhone.testWork(new Cal() {
            @Override
            public double work(double n1, double n2) {
                return n1+n2;
            }
        },10,8);
        CellPhone cellPhone2 = new CellPhone();
        //匿名内部类的特征是可以作为参数传递
        cellPhone.testWork(new Cal() {
            @Override
            public double work(double n1, double n2) {
                return n1*n2;
            }
        },10,8);
    }
}
interface Cal{
    public double work(double n1,double n2);
}
class CellPhone{
    public void testWork(Cal cal,double n1,double n2){
        double work = cal.work(n1, n2);
        System.out.println(work);
    }
}


j局部内部类:

内部类在方法中

package com.hspedu.override_;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HomeWork06 {
    public static void main(String[] args) {
        new C().f1();
    }
}
class C{
    private String name="hello";

    public void f1(){
        class D{
            public void show(String name){
                System.out.println(name+C.this.name);
            }
        }
        D d = new D();
        d.show("唐波");

    }
}

平时用马,过河用船:

过火焰山做飞机:

package com.hspedu.override_;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HomeWork07 {
    public static void main(String[] args) {
        Person tang = new Person("唐波", new Horse());
        tang.common();
        tang.passRiver();
        tang.common();
        tang.passHill();
    }
}
interface Vehicles{
    public void work();
}
class Plane implements Vehicles{

    @Override
    public void work() {
        System.out.println("过火焰山用飞机...");
    }
}
class Horse implements Vehicles {
    @Override
    public void work() {
        System.out.println("平常用马");
    }
}
class Boat implements Vehicles{
    @Override
    public void work() {
        System.out.println("过河用船");
    }
}
class VehiclesFactory{
    private VehiclesFactory() {
    }

    private static Horse horse=new Horse();
    public static Horse getHorse(){
        return horse;
    }
    public static Boat getBoat(){
        return new Boat();
    }
    public static Plane getPlane(){
        return new Plane();
    }

}
class Person{
    private String name;
    private Vehicles vehicles;

    public Person(String name, Vehicles vehicles) {
        this.name = name;
        this.vehicles = vehicles;
    }
    public void passRiver(){
        if(!(vehicles instanceof Boat)){
            vehicles=VehiclesFactory.getBoat();
        }
        vehicles.work();
    }
    public void common(){
        if(!(vehicles instanceof Horse)){
            vehicles=VehiclesFactory.getHorse();
        }
        vehicles.work();
    }
    public void passHill(){
        if(!(vehicles instanceof Plane)){
            vehicles=VehiclesFactory.getPlane();
        }
        vehicles.work();
    }
}

异常处理快捷键CTRL+ALT+T

String常用方法:

package com.hspedu.string_;

import java.util.Locale;

/**
 * @author 唐波~
 * @version 1.0
 */
public class String01 {
    public static void main(String[] args) {
        String str1="hello";
        String str2="Hello";
        System.out.println(str1.equals(str2));
        System.out.println(str1.equalsIgnoreCase(str2));
        System.out.println(str1.length());
        System.out.println(str1.substring(2,4));
        System.out.println(str1.toUpperCase(Locale.ROOT));
        System.out.println(str2.toLowerCase(Locale.ROOT));
        System.out.println(str1+str2);



        if ("Hell".equalsIgnoreCase(str1)){
            System.out.println("success");
        }else{
            System.out.println("false");
        }
        int index=str1.lastIndexOf("l");
        System.out.println(index);

        String s="happy";
        char[] chars=s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }

        String poem="锄禾日当午,汗滴禾下土,谁知盘中餐,粒粒皆辛苦";
        String[] split=poem.split(",");
        for (int i = 0; i < split.length; i++) {
            System.out.println(split[i]);
        }

        String a="ja";
        String c="jc";
        String b="jack";
        System.out.println(b.compareTo(a));
        System.out.println(a.compareTo(c));

        String name="波波";
        int age=25;
        //%s字符串;%d整数;%.2f保留两位小数,并且四舍五入;%c使用char类型
        String formaStr="我的姓名是%s年纪是%d";
        String info=String.format(formaStr,name,age);
        System.out.println(info);
    }
}

StringBuffer的简单介绍:

public class StringBuffer_ {
    public static void main(String[] args) {
        //StringBuffer的构造器1
        StringBuffer stringBuffer = new StringBuffer();

        //通过构造器指定char[]的大小
        StringBuffer stringBuffer2 = new StringBuffer(100);

        //通过给一个String创建StringBuffer,容量长度wei字符串长度+16
        StringBuffer hello = new StringBuffer("hello");
    }
}

StringBuffer和String的转换:

package com.hspedu.stringbuffer_;

/**
 * @author 唐波~
 * @version 1.0
 */
public class StringAndStringBuffer {
    public static void main(String[] args) {
        //方式一:使用构造器,返回的才是StringBuffer对象,对str本身没有影响
        String str="hello";
        StringBuffer stringBuffer = new StringBuffer(str);
        
        //方式二,string 转到StringBuffer
        StringBuffer stringBuffer1 = new StringBuffer();
        StringBuffer append = stringBuffer1.append(str);

        //方式3,StringBuffer到string
        StringBuffer stringBuffer2 = new StringBuffer("韩顺平教育");
        String s = stringBuffer2.toString();
        
        //方式4,使用构造器搞定
        String s1=new String(stringBuffer2);
    }
}

StringBuffer插入:insert

在后面追加:.append("hahah")       append+空   不会返回异常,源码是将mull转换成字符 n   u  l  l

删除.delete(11,14)

替换.replace(9,11,"周子咯")

public class StringInsert {
    public static void main(String[] args) {
        StringBuffer s=new StringBuffer("张胜丰");
        //StringBuffer插入
        s.insert(1,"赵敏");
        System.out.println(s);
        System.out.println(s.indexOf("张胜丰"));

    }
}

数值的每三位加一个逗号:

package com.hspedu.stringbuffer_;



import java.util.Scanner;

/**
 * @author 唐波~
 * @version 1.0
 */
public class StringBufferExercise {
    public static void main(String[] args) {
//        Scanner scanner = new Scanner(System.in);
        String price="12989825653564.59";
        StringBuffer stringBuffer = new StringBuffer(price);
        //找到小数点的索引,然后再该位置的前三位插入逗号
        //做循环
//        int i = stringBuffer.lastIndexOf(".");
//        stringBuffer.insert(i-3,",");
//        System.out.println(stringBuffer);
        for(int i = stringBuffer.lastIndexOf(".")-3;i>0;i-=3){
            stringBuffer.insert(i,",");
        }
        System.out.println(stringBuffer);

    }
}

sort的使用:以及Arrays.toString

package com.hspedu.arrays_;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ArrayMethod01 {
    public static void main(String[] args) {
        Integer[] integers={6,20,3};
        int arrs[]={3,5,6,8};
//        System.out.println(Arrays.toString(integers));
//        System.out.println(Arrays.toString(arrs));

        Arrays.sort(integers);//默认排序
        System.out.println(Arrays.toString(integers));

        //自定义排序,从小到大
        Arrays.sort(integers, new Comparator() {//匿名内部类
            @Override
            public int compare(Object o1, Object o2) {
                Integer i1 = (Integer) o1;
                Integer i2 = (Integer) o2;
                return i2-i1;
            }
        });
        System.out.println(Arrays.toString(integers));
        
        //因为数组是引用类型,通过sort排序后会影响到实参integers
        for (int i = 0; i < integers.length; i++) {
            System.out.print(integers[i]);
        }

    }
}

Arrays自定义模拟排序:

i1-i2从小到大

i2-i1从大到小

package com.hspedu.arrays_;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ArrayMethod02 {
    public static void main(String[] args) {
        int arr[] = {-1, 2, 1, 6, 8, 99, 4, 55};
        bubble(arr, new Comparator() {//接口调用
            @Override
            public int compare(Object o1, Object o2) {
                int i1=(Integer)o1;//拆箱
                int i2=(Integer)o2;
                return i2-i1;
            }
        });

        System.out.println(Arrays.toString(arr));
    }

    public static void bubble(int[] arr, Comparator c) {//接口
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (c.compare(arr[j],arr[j+1])>0) {//接口调用
                    int temp = 0;
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

Arrays的而二分查找,查找索引:

二分查找必须是有序数组

//拷贝数组,数组长度自定义

数组的填充

判断数组是否一致

打印成集合

package com.hspedu.arrays_;

import java.util.Arrays;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ArrayMethod03 {
    public static void main(String[] args) {
        Integer arr[]={1,2,6,9,123,156};
        int index=Arrays.binarySearch(arr,123);
        System.out.println(index);

        Integer newArr[]=Arrays.copyOf(arr,arr.length);//拷贝数组,数组长度自定义
        System.out.println(Arrays.toString(newArr));


        Integer num[]=new Integer[]{9,3,2};//数组的填充
        Arrays.fill(num,99);
        System.out.println(Arrays.toString(num));

        Integer arr2[]={1,2,6,9,123,156};//比较数组是否一致
        boolean equals=Arrays.equals(arr,arr2);//一致返回为真,数组1,数组2
        System.out.println(equals);

        List aslist=Arrays.asList(2,3,4,5,3);//打印成集合
        System.out.println(aslist);
        System.out.println(aslist.getClass());//查看运行类型
    }
}

Array用数组排序:按照价格的大小输出:

package com.hspedu.arrays_;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ArrayExercise01 {
    public static void main(String[] args) {
        Book books[]=new Book[4];
        books[0]=new Book("红楼梦",25);
        books[1]=new Book("红楼梦2",65);
        books[2]=new Book("红楼梦3",35);
        books[3]=new Book("红楼梦4",96);

        Arrays.sort(books, new Comparator() {//对数组排序
            @Override
            public int compare(Object o1, Object o2) {
                Book book1=(Book)o1;
                Book book2=(Book)o2;
                //return book2.getName().length()-book1.getName().length();//重大到小
                double priceVal=book2.getPrice()-book1.getPrice();
                if(priceVal>0){
                    return 1;
                }else if(priceVal<0){
                    return -1;
                }else {
                    return 0;
                }
            }
        });
        System.out.println(Arrays.toString(books));
    }
}
class Book{
    private String name;
    private double price;

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}

第一代日期:

Date输出系统时间,指定时间格式,转换时间格式:

把String转换成Date格式的时候,格式要对得上,你给的String格式一样

SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");

String s="2022年01月06日 09:09:15 周四";

package com.hspedu.date_;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Data01 {
    public static void main(String[] args) throws ParseException {
        Date date = new Date();//系统时间
        System.out.println(date);
        Date date1 = new Date(965555);//毫秒数指定时间
        System.out.println(date1);

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");
        String format=sdf.format(date);
        System.out.println(format);

        String s="2022年01月06日 09:09:15 周四";
        Date parse= sdf.parse(s);//转格式
        System.out.println(parse);
    }
}

第二代日期:

package com.hspedu.date_;

import java.util.Calendar;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Calendar_ {
    public static void main(String[] args) {
        //Calendar是一个抽象类并且构造器是私有的
        //2.可以通过getInstance()方法获取实例
        Calendar instance = Calendar.getInstance();
        //自己组合输出方式
        System.out.println(instance.get(Calendar.YEAR)+"年"+(instance.get(Calendar.MONTH)+1)+"月");
        System.out.println(instance.get(Calendar.MONTH)+1);//月份默认从0开始
        System.out.println(instance.get(Calendar.MINUTE));//分
        System.out.println(instance.get(Calendar.SECOND));//秒
        System.out.println(instance.get(Calendar.DAY_OF_MONTH));//第几天
        System.out.println(instance.get(Calendar.HOUR_OF_DAY));//24小时制
    }
}

第三代日期:LocalDate(年月日),,,LocalTime(时分秒),,,LocalDateTime(年月日时分秒)

Calendar的弱势

1)可变性,时间日期应该不可变才对

2)偏移性,年份都是1990起,但是月份是从0开始

3)格式化只对date有用

3)线程不安全,不能处理闰秒,每两天多一秒

package com.hspedu.date_;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author 唐波~
 * @version 1.0
 */
public class LocalDate_ {
    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        System.out.println(now);

        LocalDateTime now2=LocalDateTime.now();
        System.out.println(now2);
        System.out.println(now2.getMonth());//英文月
        System.out.println(now2.getMonthValue());//数字月
        System.out.println(now2.getYear());
        System.out.println(now2.getDayOfMonth());//天
    }
}

自定义格式返回年月日时分秒

package com.hspedu.date_;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 唐波~
 * @version 1.0
 */
public class LocalDate_ {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);

        //使用DateTimeFormat对时间日期格式化
        DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss");
        String format = dtf.format(now);//放进去返回的对象才是格式化的
        System.out.println(format);
//
//        LocalDateTime now2=LocalDateTime.now();
//        System.out.println(now2);
//        System.out.println(now2.getMonth());//英文月
//        System.out.println(now2.getMonthValue());//数字月
//        System.out.println(now2.getYear());
//        System.out.println(now2.getDayOfMonth());//天
    }
}

任意数组任意位置的翻转:太奇妙了

package com.hspedu.string_fanzhuan;

/**
 * @author 唐波~
 * @version 1.0
 */
public class FanZhuan {
    public static void main(String[] args) {
        String str="abcdef";
        System.out.println(str);//交换前的STR
        str=reverse(str,1,4);
        System.out.println(str);
    }
    public static String reverse(String str,int start,int end){
        char[] chars=str.toCharArray();
        char temp=' ';//交换辅助变量
        for (int i = start,j =end ; i<j;  i++,j--) {
            temp=chars[i];
            chars[i]=chars[j];
            chars[j]=temp;
        }
        //使用chars重新构建一个String返回
        return new String(chars);
    }
}

代码优化,加入输入异常处理:

package com.hspedu.string_fanzhuan;

/**
 * @author 唐波~
 * @version 1.0
 */
public class FanZhuan {
    public static void main(String[] args) {
        String str="Hello";
        System.out.println(str);//交换前的STR
        try {
            str=reverse(str,0,41);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return;
        }
        System.out.println(str);
    }
    public static String reverse(String str,int start,int end){
        if(!(str !=null&&start>=0&&end>start&&end<str.length())){
            throw new RuntimeException("参数不正确");

        }

        char[] chars=str.toCharArray();
        char temp=' ';//交换辅助变量
        for (int i = start,j =end ; i<j;  i++,j--) {
            temp=chars[i];
            chars[i]=chars[j];
            chars[j]=temp;
        }
        //使用chars重新构建一个String返回
        return new String(chars);
    }
}

邮箱注册:

package com.hspedu.zhuce;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ZhuCe {
    public static void main(String[] args) {
        try {
            userRegister("bobo","66666","1@3.");
            System.out.println("注册成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());;
        }

    }
    public static void userRegister(String name,String pwd,String email){
        //第一关验证名字
        if(name==null||pwd==null||email==null){
            throw new RuntimeException("用户名,密码,邮箱不能为空");
        }
        if(!(name.length()==2|name.length()==3|name.length()==4)){
            throw new RuntimeException("用户名是错的");
        }
        if (!(pwd.length()==6|isDigital(pwd))){
            throw new RuntimeException("密码长度不正确或者不全是数字");
        }
        int index=email.indexOf('@');//找索引.的索引要比@大则判断出@在前
        int index2=email.indexOf('.');
        if (!(email.contains("@")&&email.contains(".")&&index2>index)){
            throw new RuntimeException("邮箱格式不对");
        }

    }
    public static boolean isDigital(String str){
        char chars[]=str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i]<'0'||chars[i]>'9'){
                System.out.println("你的密码应该是数字");
                return false;
            }
        }
        return true;
    }
}

字符串的分割以及格式化的输出:

"Han shun Ping";

输出为:Ping,Han .S

package com.hspedu.string_input;

import java.util.Locale;

/**
 * @author 唐波~
 * @version 1.0
 */
public class OutPutName {
    public static void main(String[] args) {
        String name="Han shun Ping";
        printName(name);
    }
    public static void printName(String str){
        //对输入逗号字符串进行分割spilt(" ")
        //对分割得到的数组String[]进行格式化String.format()
        if(str==null){
            throw new RuntimeException("str不能为空");
        }
        String[] s = str.split(" ");//按照空格分割
        if(s.length!=3){
            throw new RuntimeException("字符串要是三个部分");
        }
        String format = String.format("%s,%s .%c", s[2], s[0], s[1].toUpperCase().charAt(0));
        System.out.println(format);

    }
}

字符串统计,判断字符串有多少个大小写,多少个数字

package com.hspedu.string_input;

/**
 * @author 唐波~
 * @version 1.0
 */
public class DaXiaoXie {
    public static void main(String[] args) {
        String str="AghjdgfjhdsgBjhashdj@@@985&&&";
        panDuan(str);
    }
    public static void panDuan(String str){
        if (str==null){
            System.out.println("字符串为空");
            return;
        }
        char chars[]=str.toCharArray();
        int numCount=0;
        int lowerCount=0;
        int upperCount=0;
        int otherCount=0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i)>='0'&&str.charAt(i)<='9'){
                numCount++;
            }else if(str.charAt(i)>='a'&&str.charAt(i)<'z'){
                lowerCount++;
            }else if(str.charAt(i)>='A'&&str.charAt(i)<'Z'){
                upperCount++;
            }else{
                otherCount++;
            }
        }
        System.out.println("数字有"+numCount);
        System.out.println("大写字母有"+upperCount);
        System.out.println("小写字母有"+lowerCount);
        System.out.println("其他f符号"+otherCount);
    }
}
//输入字符串,判断有多少个大写字母,小写字母,多少个数字  提示ASSCI

Java集合:

package com.hspedu.collection_;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 唐波~
 * @version 1.0
 */
public class CollectionMethod {
    public static void main(String[] args) {
        List list=new ArrayList();
        list.add("jack");
        list.add(10);
        System.out.println(list);

        list.remove("jack");
        System.out.println(list);

        System.out.println(list.contains("jack"));
        System.out.println(list.size());

        System.out.println(list.isEmpty());
        list.clear();
        System.out.println(list);

        ArrayList arrayList = new ArrayList();
        arrayList.add("红楼");
        arrayList.add("南楼");
        list.addAll(arrayList);
        System.out.println(list);
        System.out.println(list.containsAll(arrayList));
        list.removeAll(arrayList);
        System.out.println(list);
    }
}

增强FOR循环:

package com.hspedu.collection_;
/**
 * @author 唐波~
 * @version 1.0
 */
public class CollectionFor {
    public static void main(String[] args) {
        int nums[]={1,2,6,5,8,5,7,};
        for (int i :nums){
            System.out.print(i+" ");
        }
    }
}

迭代器和增强for循环:

package com.hspedu.collection_;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 唐波~
 * @version 1.0
 */
public class CollectionExercise {
    public static void main(String[] args) {
        List arrayList = new ArrayList();
        arrayList.add(new Dog("yy",5));
        arrayList.add(new Dog("ll",6));

        System.out.println("增强FOR循环");
        for (Object o :arrayList) {
            System.out.println(o);
        }

        System.out.println("迭代器");
        Iterator iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }

    }
}
class Dog{
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Java_List:

package com.hspedu.collection_list;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 唐波~
 * @version 1.0
 */
public class List_ {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("jack");
        list.add("ton");
        list.add("mary");
        list.add("jk");
        //插入
        list.add(2,"jack");
        System.out.println(list);
        System.out.println(list.get(2));
        List list2 = new ArrayList();
        list2.add("iii");
        list2.addAll(0,list);
        System.out.println(list2);
        System.out.println(list2.indexOf("ton"));
        System.out.println(list2.lastIndexOf("jack"));
        list2.set(1,"marrtsjhdhjs");
        System.out.println(list2);
        List list3=list2.subList(2,4);
        System.out.println(list3);
    }
}

java_list练习:

package com.hspedu.collection_list;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 唐波~
 * @version 1.0
 */
public class List2_ {
    public static void main(String[] args) {
        List list=new ArrayList();
        for (int i = 0; i < 12; i++) {
            list.add("hello"+i);
        }
        System.out.println(list);
        list.add(1,"boob");
        System.out.println(list);
        System.out.println(list.get(4));
        list.remove(5);
        System.out.println(list);
        list.set(6,"hjsadfgjhsag");//修改
        System.out.println(list);

        Iterator iterator = list.iterator();//迭代器
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println(next);
        }
        System.out.println("增强");
        for (Object o :list) {
            System.out.println(o);

        }


    }
    }

重写hashcode:

hashSet加入元素

package com.hspedu.hashset01;

import java.util.HashSet;
import java.util.Objects;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HashSet01 {
    public static void main(String[] args) {
        HashSet hashSet = new HashSet();
        hashSet.add(new Employee("bobo",25));
        hashSet.add(new Employee("bobo",25));
        hashSet.add(new Employee("bobo2",26));
        System.out.println(hashSet);
    }
}
class Employee{
    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return age == employee.age && Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

韩顺平hashSet练习题2:

注意点:两个类里面都要重写hashCode

class Employee{
    private String name;
    private double sal;
    private MyDate birthday;

package com.hspedu.hashset02;

import java.util.HashSet;
import java.util.Objects;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HashSet02 {
    public static void main(String[] args) {
        HashSet hashSet = new HashSet();
        hashSet.add(new Employee("bobo",25,new MyDate(2012,12,5)));
        hashSet.add(new Employee("bobo",26,new MyDate(2012,12,5)));
        System.out.println(hashSet);
    }
}
class Employee{
    private String name;
    private double sal;
    private MyDate birthday;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return Objects.equals(name, employee.name) && Objects.equals(birthday, employee.birthday);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, birthday);
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday +
                '}';
    }

    public MyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

    public Employee(String name, double sal, MyDate birthday) {
        this.name = name;
        this.sal = sal;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    public Employee(String name, double sal) {
        this.name = name;
        this.sal = sal;
    }
}
class MyDate{
    private int year;
    private int month;
    private int day;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyDate myDate = (MyDate) o;
        return year == myDate.year && month == myDate.month && day == myDate.day;
    }

    @Override
    public int hashCode() {
        return Objects.hash(year, month, day);
    }

    @Override
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }
}

Java——Map存取键值对

map.put

map.get("")

package com.hspedu.hashmap_;

import java.util.HashMap;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HashMap_ {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        hashMap.put("n2","6");
        hashMap.put("n1",5);
        hashMap.put("n3","7");
        hashMap.put("bobo","7");
        System.out.println(hashMap);
        System.out.println(hashMap.get("n1"));
    }
}

Key和Value是存放在HashMap$NODE里面,set和collection只是做了映射(指向),取出key和value的值,为了方便遍历,还会处绽放一个entrySet集合,元素的类型为entry,一个entry对象包含了key,value       ,        Map.Entry提供了两个自己重要的方法getKey()和getValue();

package com.hspedu.hashmap_;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HashMap_ {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        hashMap.put("n2","6");
        hashMap.put("n1",5);
        hashMap.put("n3","7");
        hashMap.put("bobo","7");
        System.out.println(hashMap);
        System.out.println(hashMap.get("bobo"));

        Set set = hashMap.entrySet();
        System.out.println(set.getClass());
        for (Object o :set) {
            System.out.println(o);
            System.out.println(o.getClass());

            Map.Entry entry=(Map.Entry)o;
            System.out.println(entry.getKey()+" "+entry.getValue());
        }
    }
}

a遍历取出集合的key和value:

package com.hspedu.hashmap_;

import java.util.HashMap;
import java.util.Set;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HashMap02 {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        hashMap.put("n2","6");
        hashMap.put("n1",5);
        hashMap.put("n3","7");
        hashMap.put("bobo","7");

        //方法一
        Set set = hashMap.keySet();//取出key
        for (Object o :set) {
            System.out.println(o+" "+hashMap.get(o));//遍历取出key和Value
        }
         //方法二:
        Iterator iterator=set.iterator();
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println(next+" "+hashMap.get(next));
        }

        Collection values = hashMap.values();//取出所有的值
        for (Object o :values) {
            System.out.println(o);
        }

        Set set1 = hashMap.keySet();//取出所有的key
        for (Object o :set1) {
            System.out.println(o);
        }


    }
}

 取工资超过一万的:增强for和迭代器,Map练习:

package com.hspedu.hashmap_;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HashMap04 {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        hashMap.put(1,new Emp("bobo",300000,1));
        hashMap.put(2,new Emp("bobo",60000,2));
        hashMap.put(3,new Emp("bobo",3000,3));

        Set set = hashMap.keySet();//遍历打印工资超过一万的
        for (Object o :set) {
            Emp emp=(Emp)hashMap.get(o);//获取value
            if(emp.getSal()>10000){
                System.out.println(o+"+"+hashMap.get(o));
            }
        }

        Set set1 = hashMap.entrySet();
        Iterator iterator = set1.iterator();//迭代器排序
        while (iterator.hasNext()) {
            Map.Entry next =  (Map.Entry)iterator.next();
            //通过next取得key和value
            Emp value = (Emp )next.getValue();
            if(value.getSal()>10000){
                System.out.println(next);
            }


        }

    }
}
class Emp{
    private String name;
    private double sal;
    private int id;

    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", id=" + id +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Emp(String name, double sal, int id) {
        this.name = name;
        this.sal = sal;
        this.id = id;
    }
}

c重写hashMap的hash_code方法,证明Hash_Map的扩容条件是     链表>8且表>64:

    @Override
    public int hashCode() {
        return 100;
    }//强制放到同一个链表中

用debug证明,另外证明表的扩容    IDEA调试设置:IDEA中Dubugger设置_csp732171109的博客-CSDN博客

package com.hspedu.hashmap_;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HashMap05 {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        for (int i = 0; i <=97; i++) {
            hashMap.put(new A(i),"hello");
        }
        System.out.println(hashMap);
    }
}
class A{
    private int num;

    @Override
    public String toString() {
        return "\nA{" +
                "num=" + num +
                '}';
    }

    @Override
    public int hashCode() {
        return 100;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public A(int num) {
        this.num = num;
    }
}

使用TreeSet按字符串长度排序:实现Comparator接口的匿名对象(匿名内部类)

1-------return ((String)o1).length()-((String)o2).length();//长度

2-----------return ((String)o1).compareTo((String)o2);//从小到大 ASCII表


package com.hspedu.treeset_;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * @author 唐波~
 * @version 1.0
 */
public class TreeSet_ {
    public static void main(String[] args) {
        TreeSet treeSet = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).compareTo((String)o2);
            }
        });
        treeSet.add("jack44444");
        treeSet.add("jack11");
        treeSet.add("jack333");
        treeSet.add("jacksfdadsdaasdf");
        System.out.println(treeSet);
    }
}

Collections工具类的使用1:

package com.hspedu.collections_;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Collections_ {
    public static void main(String[] args) {
        ArrayList collection = new ArrayList();
        collection.add("bobo");
        collection.add("milan");
        collection.add("smi");

        Collections.reverse(collection);//翻转排序
        System.out.println(collection);

        Collections.shuffle(collection);//打乱排序
        System.out.println(collection);

        Collections.sort(collection);//自然排序
        System.out.println(collection);

        Collections.sort(collection, new Comparator() {//创建比较器
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).length()-((String)o2).length();
            }
        });
        System.out.println(collection);

        Object max=Collections.max(collection, new Comparator() {//长度最大的
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).length()-((String)o2).length();
            }
        });
        System.out.println(max);

        Object fre=Collections.frequency(collection,"bobo");//出现次数
        System.out.println(fre);

        System.out.println(Collections.max(collection));//按照自然排序、字母大小

        ArrayList dest=new ArrayList();//dest现在还是空集合
        for (int i = 0; i < collection.size(); i++) {//床架一样大的集合
            dest.add(" ");

        }
        Collections.copy(dest,collection);//拷贝集合到dest
        System.out.println(dest);

        Collections.replaceAll(collection,"bobo","leilei");//替换
        System.out.println(collection);
    }
}

打印标题,超过十五的字的只显示十五个字:

package com.hspedu.homework01;

import java.util.ArrayList;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HomeWork01 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(new News("bobo","波波还活着"));
        arrayList.add(new News("lelelele是波波的弟弟阿三顶顶顶顶顶顶顶顶","lele是波波的弟弟阿三顶顶顶顶顶顶顶顶"));

        int size= arrayList.size();
        for (int i = size-1; i >= 0; i--) {
            News news=(News)arrayList.get(i);
            System.out.println("这是title      "+   processTitle(news.getTitle()));
        }
    }
    public static String processTitle(String title){
        if(title==null){
            System.out.println("标题为空");
        }
        if(title.length()>15){
            return title.substring(0,14)+"...";
        }else {
            return title;
        }
    }
}
class News{
    private String title;
    private String content;

    public News() {

    }

    @Override
    public String toString() {
        return "News{" +
                "title='" + title + '\'' +
                '}';
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public News(String title, String content) {
        this.title = title;
        this.content = content;
    }
}

zz自己重新敲的:如果标题大于五个字符则返回...

package com.hspedu.homework03;

import java.util.ArrayList;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HomeWork03 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(new News("bobo","bobo真好"));
        arrayList.add(new News("bobo12345678912","bobo真好"));

        for (int i = 0; i < arrayList.size(); i++) {
            News news = (News) arrayList.get(i);
            System.out.println(processTitle(news.getTitle()));
        }
    }
    public static String processTitle(String title){
        if(title==null){
            return "这是一个空集合";
        }
        if (title.length()>5){
            return title.substring(0,4)+"...";
        }else {
            return title;
        }
    }
}
class News{
    private String title;
    private String content;

    @Override
    public String toString() {
        return "News{" +
                "title='" + title + '\'' +
                '}';
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public News(String title, String content) {
        this.title = title;
        this.content = content;
    }
}

用Map或者HashMap给每人涨工资:

        Set set = hashMap.keySet();//hashMap遍历用KeySet()比较方便
        for (Object o :set) {//取出key o,用get(o)获取值
            hashMap.put(o,(Integer)hashMap.get(o)+100);//向下转型,double转为Integer
        }
        System.out.println(hashMap);

package com.hspedu.homework05;

import java.util.*;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HomeWork05 {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        hashMap.put("jack",650);//自动装箱int>>Integer
        hashMap.put("tom",1200);
        hashMap.put("smith",3900);
        System.out.println(hashMap.get("jack" ));
        System.out.println(hashMap);

        hashMap.put("jack",2600);
        System.out.println(hashMap);

        Set set = hashMap.keySet();//hashMap遍历用KeySet()比较方便
        for (Object o :set) {//取出key o,用get(o)获取值
            hashMap.put(o,(Integer)hashMap.get(o)+100);//向下转型,double转为Integer
        }
        System.out.println(hashMap);

        Set set1 = hashMap.entrySet();//entryset的使用
        Iterator iterator = set1.iterator();
        while (iterator.hasNext()) {
            //Map.Entry next=(Map.Entry)iterator.next();
            Map.Entry entry = (Map.Entry)iterator.next();//本质是Entry
            System.out.println(entry.getKey()+" "+entry.getValue());
        }
        Collection values = hashMap.values();//取出来值,遍历所有工资
        for (Object o :values) {
            System.out.println(o);

        }


    }
//    public static double jia(double jia){
//        for (int i = 0; i < 3; i++) {
//
//        }return va
//    }
}
class Emp{
    public Emp() {
    }

    private String name;
    private double sal;

    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    public Emp(String name, double sal) {
        this.name = name;
        this.sal = sal;
    }
}

HashSet是如何去重的:

                底层是HashMap;   HashCode()+equals(),底层先通过存入对象,进行运算得到一个hash值,然后得到对应的索引,索引如果有元素则对比,不相同则放在链后,相同则不加入;equals是程序员定义的。

TreeSet的去重机制:

                 如果你传入了一个匿名对象,new Compartor,就使用实现的compare,如果比较的结果是0则不添加,r认为是一个对象

                 如果没传入匿名对象,则默认用Comparable接口的compareTo对象去重,默认比较字符串首字母大小

!!!!!!!!!!!!!!!!!!!!!!    TreeSet的add方法,构造器new Person()没有传入Compartor接口的匿名内部类,所以在底层他会尝试给你转成Comparable类型;会报错ClassCastException

TreeSet treeSet=tnew TreeSet();

tree.add(new Person());

解决方法:Class Person implements Comparable;

//向下转型,为了调用Dog的方法

ArrayList arrayList = new ArrayList<Dog>();
arrayList.add(new Dog("旺财",25));
arrayList.add(new Dog("小白",20));
arrayList.add(new Dog("小hei",18));
arrayList.add(new Cat("猫猫",25));
for (Object o :arrayList) {
    Dog dog=(Dog) o;//向下转型,为了调用Dog的方法
    System.out.println(dog.getName()+dog.getAge());
}

 泛型的初步使用:

package com.hspedu.generic02_;

import java.util.ArrayList;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Generic02 {
    public static void main(String[] args) {
        //使用泛型<Dog>,存放在集合中的只能是Dog类型
        ArrayList<Dog> arrayList = new ArrayList<Dog>();
        arrayList.add(new Dog("旺财",25));
        arrayList.add(new Dog("小白",20));
        arrayList.add(new Dog("小hei",18));
//        arrayList.add(new Cat("猫猫",25));
        //使用泛型的方法解决,可以直接用Dog
        for (Dog o :arrayList) {
            //for (Object o :arrayList) {//这是以前的
//                  Dog dog=(Dog) o;//向下转型,为了调用Dog的方法//原来的
            System.out.println(o.getName()+o.getAge());
        }

    }
}
class Dog{
    private String name;
    private int age;



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
class Cat{
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

泛型的入门加初步排序sort:

package com.hspedu.genreic04_;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Generic04 {
    public static void main(String[] args) {
        ArrayList<Dog> dogs = new ArrayList<>();
        dogs.add(new Dog("小白",6));
        dogs.add(new Dog("小黑",7));
        dogs.add(new Dog("小黄",3));

        dogs.sort(new Comparator<Dog>() {
            @Override
            public int compare(Dog o1, Dog o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        for (Dog o :dogs) {
            System.out.println(o.getAge()+o.getName());
        }
    }
}
class Dog{
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

泛型的使用两个泛型指定,已经泛型中迭代器和增强FOR循环的用法,注意For循环是怎么输出内容的:

HashMap<String, Dogs> stringDogsHashMap = new HashMap<String, Dogs>();

package com.hspedu.generic04_;

import java.util.*;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Generic04 {
    public static void main(String[] args) {
        ArrayList<Dogs> dogs = new ArrayList<>();
        dogs.add(new Dogs("小白",4));
        dogs.add(new Dogs("小hei",3));
        dogs.add(new Dogs("小黄",6));

        dogs.sort(new Comparator<Dogs>() {
            @Override
            public int compare(Dogs o1, Dogs o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        for (Dogs dog :dogs) {
            System.out.println(dog.getAge()+dog.getName());
        }

        HashMap<String, Dogs> stringDogsHashMap = new HashMap<>();
        stringDogsHashMap.put("小黑1",new Dogs("小黑1",3));
        stringDogsHashMap.put("小黑2",new Dogs("小黑2",3));
        stringDogsHashMap.put("小黑3",new Dogs("小黑3",3));
        Set<String> strings = stringDogsHashMap.keySet();
        for (Object o :strings) {//泛型增强FOR循环用法KeySet
            System.out.println(stringDogsHashMap.get(o));//注意是怎么输出的
        }


        System.out.println("==========================");
        Set<Map.Entry<String, Dogs>> entries = stringDogsHashMap.entrySet();
        Iterator<Map.Entry<String, Dogs>> iterator = entries.iterator();
        while (iterator.hasNext()) {//泛型迭代器用法,entrySet
            Map.Entry<String, Dogs> next =  iterator.next();//泛型迭代器用法
            System.out.println(next.getKey()+" "+next.getValue());

        }


    }
}
class Dogs{
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Dogs(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dogs{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

f  ------泛型的课堂练习:注意点

        ArrayList<Employee> employees = new ArrayList<>();
        employees.add(new Employee("bobo11",10000,new MyDate(8,18,1996)));
        employees.add(new Employee("lele",8000,new MyDate(8,18,1996)));
        employees.add(new Employee("xuLei",6000,new MyDate(8,18,1996)));
 

package com.hspedu.Generic07;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Generic07 {
    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<>();
        employees.add(new Employee("bobo11",10000,new MyDate(8,18,1996)));
        employees.add(new Employee("lele",8000,new MyDate(8,18,1996)));
        employees.add(new Employee("xuLei",6000,new MyDate(8,18,1996)));

        employees.sort(new Comparator<Employee>() {
            @Override
            public int compare(Employee o1, Employee o2) {
               return o2.getName().length()-o1.getName().length();
//                return o1.getSal()-o2.getSal();
            }
        });
        for (Employee employee :employees) {
            System.out.println(employee.getName()+" "+employee.getBirthday()+employee.getSal());
        }

    }
}
class Employee{
    private String name;
    private int sal;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSal() {
        return sal;
    }

    public void setSal(int sal) {
        this.sal = sal;
    }

    public MyDate getBirthday() {
        return birthday;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday +
                '}';
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

    public Employee(String name, int sal, MyDate birthday) {
        this.name = name;
        this.sal = sal;
        this.birthday = birthday;
    }

    private MyDate birthday;
}
class MyDate{
    private int month;
    private int day;
    private int year;

    @Override
    public String toString() {
        return "MyDate{" +
                "month=" + month +
                ", day=" + day +
                ", year=" + year +
                '}';
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

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

z在java里画圆的步骤:

点击红X结束进程

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

1.先定义一个面板(画板)继承JPanel类,
2.Graphics g  看成画笔,提供很多绘图方法

3.重写画笔

4.将画板设置为空private MyPanel mp =null;

5.定义一个画画的方法:

    public DrawCircle(){
        mp=new MyPanel();//初始化面板
        this.add(mp);//把面板放入到画框
        this.setSize(400,300);//设置窗口大小
        this.setVisible(true);//可视化
    }

6.

new DrawCircle();
package com.hspedu.tank_.drawcircle;

import javax.swing.*;
import java.awt.*;

/**
 * @author 唐波~
 * @version 1.0
 * 在面板上画圆
 */
public class DrawCircle extends JFrame{//理解成画框
    private MyPanel mp =null;
    public static void main(String[] args) {
        new DrawCircle();
    }
    public DrawCircle(){
        //初始化面板
        mp=new MyPanel();
        //把面板放入到画框
        this.add(mp);
        //设置窗口大小
        this.setSize(400,300);
        this.setVisible(true);//可视化
    }
}
//1.先定义一个面板(画板)继承JPanel类,
//2.Graphics g  看成画笔,提供很多绘图方法
// 首先重写paint
class MyPanel extends JPanel{
    @Override
    public void paint(Graphics g) {
        super.paint(g);//一定要保留,完成初始化
        g.drawOval(10,10,100,100);//画圆
    }
}

Java里面的各种画图:

package com.hspedu.tank_.drawcircle;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 * 在面板上画圆
 */
public class DrawCircle extends JFrame{//理解成画框
    private MyPanel mp =null;
    public static void main(String[] args) {
        new DrawCircle();

    }
    public DrawCircle(){
        //初始化面板
        mp=new MyPanel();
        //把面板放入到画框
        this.add(mp);
        //设置窗口大小
        this.setSize(300,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);//可视化

    }
}
//1.先定义一个面板(画板)继承JPanel类,
//2.Graphics g  看成画笔,提供很多绘图方法
// 首先重写paint
class MyPanel extends JPanel{
    @Override
    public void paint(Graphics g) {
        super.paint(g);//一定要保留,完成初始化
        g.drawOval(10,10,100,100);//画圆
        g.drawLine(10,10,50,50);//画直线
        g.drawRect(1,1,200,200);//画矩形
        g.setColor(Color.yellow);//设置画笔颜色
        g.fillRect(90,90,100,100);//画填充矩形

        g.setColor(Color.red);
        g.drawOval(100,100,50,50);//画椭圆
        //获取图片//打开文件
        Image image= null;
        try {//打开文件
            image = ImageIO.read(new File("C:\\Users\\123\\Pictures\\Screenshots\\屏幕截图(4).png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        g.drawImage(image,10,10,200,200,this);

        g.setColor(Color.green);//写字,设置字体
        g.setFont(new Font("隶书",Font.BOLD,50));
        g.drawString("北京你好",100,100);
    }
}

画坦克包:D:\idea_java_projects\tank_

监听键盘接口:

class MyPanel extends JPanel implements KeyListener

小球移动:

    @Override//键盘按下时,该方法会触发
    public void keyPressed(KeyEvent e) {
//        System.out.println((char)e.getKeyCode()+"被按下去了");
        if(e.getKeyCode()==KeyEvent.VK_DOWN){//键盘的  下键
            y++;//向下走
        }else if (e.getKeyCode()==KeyEvent.VK_UP){
            y--;//向上走
        }
        else if (e.getKeyCode()==KeyEvent.VK_LEFT){
            x--;//向左走
        }
        else if (e.getKeyCode()==KeyEvent.VK_RIGHT){
            x++;//向右走
        }
        //面板重绘
        this.repaint();
    }

查看CPU的个数:

package com.hspedu.cpu_;

/**
 * @author 唐波~
 * @version 1.0
 */
public class CpuNum {
    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();
        int cpuNums=runtime.availableProcessors();
        System.out.println(cpuNums);
    }
}

 线程的快速入门:倒计时、、、每秒输出一次喵喵、、、或者每秒执行一个程序:

cat.start();//启动线程,,JVM调用start 0 实现多线程的机制调用run方法,,start 0 的底层是native方法,是由jvm机调用的:

进程--->>main主线程------>>>start子线程(Thread.currentThread().getName());

主线程不会阻塞,会继续执行,不用等start执行完

1.创建一个类继承线程:

2.重写run方法,做好加try//catch,用while(true)包起来,用if设置结束条件

3.new一个对象。cat.start();

package com.hspedu.threaduse;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ThreadUse01 {
    public static void main(String[] args) {
        //创建一个Cat对象,可以当做线程使用了
        Cat cat = new Cat();
        //cat.run();//如果是这样的话,这是一个普通run方法,不是并行
        cat.start();//启动线程
    }
}
class Cat extends Thread{//当一个类继承了Thread类,就可以当做线程使用
    int times=10;
    @Override//往往要重写Run方法,写上自己的业务逻辑,是实现了Runnable接口的方法
        public void run() {
        while (true) {//无限循环
            System.out.println("我是一只小喵喵"+(--times));
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);//歇一秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (times==0){
                System.out.println("倒计时结束了");
                break;
            }
        }
    }
}

使用Runnable类调用线程:

1.class Dog implements Runnable{

2.

public class ThreadUse02 {
    public static void main(String[] args) {
        Dog dog = new Dog();//创建一个对象
        Thread thread = new Thread(dog);//创建一个线程把狗丢进去
        thread.start();
    }
}
package com.hspedu.threaduse;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ThreadUse02 {
    public static void main(String[] args) {
        Dog dog = new Dog();//创建一个对象
        Thread thread = new Thread(dog);//创建一个线程把狗丢进去
        thread.start();
    }
}
class Dog implements Runnable{
    int time=0;
    @Override
    public void run() {
        while(true){
            System.out.println("我是小汪汪"+(++time));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (time==10){
                break;
            }
        }
    }
}

mo模拟调用start0():动态绑定

如果有个类已经继承了另一个另,就不能直接继承Runnbale方法,但是可以通过implements的方法实现,Tiger类实现了Runnable接口

package com.hspedu.threaduse;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ThreadUse02 {
    public static void main(String[] args) {
//        Dog dog = new Dog();//创建一个对象
//        Thread thread = new Thread(dog);//创建一个线程把狗丢进去
//        thread.start();
        Tiger tiger = new Tiger();
//        Thread thread = new Thread(tiger);
        ThreadProxy threadProxy = new ThreadProxy(tiger);
        threadProxy.start();
    }
}
class Animal{}
class  Tiger extends Animal implements Runnable{
    int times=0;

    @Override
    public void run() {
        while(true){
            System.out.println("老虎嗷嗷嗷"+(++times));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (times==10){
                break;
            }
        }
    }
}

class ThreadProxy implements Runnable{
    private Runnable target=null;

    public ThreadProxy(Runnable target) {
        this.target = target;
    }

    @Override
    public void run() {
        if(target!=null){
            target.run();//因为实现了Runnable接口
        }
    }
    public void start(){
        start0();
    }
    public void start0(){
        run();//模拟start0调取方法
    }
}

class Dog implements Runnable{
    int time=0;
    @Override
    public void run() {
        while(true){
            System.out.println("我是小汪汪"+(++time));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (time==10){
                break;
            }
        }
    }
}

最简单的多个子线程的案例:

也可以这样
        Thread thread = new Thread(a);
        Thread thread2 = new Thread(a);

package com.hspedu.threaduse;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ThreadUse03 {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        Thread thread = new Thread(a);
        Thread thread2 = new Thread(b);
        thread.start();
        thread2.start();
    }
}
class A implements Runnable {
    @Override

    public void run() {
        while (true) {
            System.out.println("小狗旺");
        }
    }
}
class B implements Runnable{
    @Override
    public void run() {
        while (true) {
            System.out.println("小猫喵喵喵");
        }
    }
}

通过通知终止线程:通知线程退出

package com.hspedu.exit_;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Exit01 {
    public static void main(String[] args) throws InterruptedException {
        T t = new T();
        t.start();
        Thread.sleep(10000);
        t.setLoop(false);
    }
}
class T extends Thread{
    int count=0;
    private boolean loop=true;
    @Override
    public void run() {
        while(loop){
            System.out.println("哈哈哈"+(++count));
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void setLoop(boolean loop) {
        this.loop = loop;
    }
}

吃包子Join的使用:

package com.hspedu.join_;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Join_ {
    public static void main(String[] args) {
        T2 t2 = new T2();
        t2.start();

        for (int i = 1; i < 20; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(i==5){
                System.out.println("吃了5个了,让子线程先吃");
                try {
                    t2.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("他吃完了,我主线程接着吃");
            }
            System.out.println("主线程吃了"+i+"个包子");
        }

    }
}
class T2 extends Thread{
    @Override
    public void run() {
        for (int i = 1; i < 20; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程吃了"+i+"个包子");
        }
    }
}

实现Runner让子线程插队:

package com.hspedu.join_;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Join02 {
    public static void main(String[] args) {
        J2 j2 = new J2();
        Thread thread = new Thread(j2);
        thread.start();

        for (int i = 0; i < 30; i++) {
            System.out.println("hi"+i);
            if(i==5){
                try {
                    thread.join();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("五个了让子线程来");
            }
        }
    }
}
class J2 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 11; i++) {
            System.out.println("hello"+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

设置守护线程:

//如希望main线程结束后子线程自动结束,需要把子线程设置为守护线程
package com.hspedu.mydaemonThread;

/**
 * @author 唐波~
 * @version 1.0
 */
public class MyDaemonThread01 {
    public static void main(String[] args) throws InterruptedException {
        MyDaemonThread myDaemonThread = new MyDaemonThread();
        Thread thread = new Thread(myDaemonThread);
        thread.setDaemon(true);
        thread.start();
        //如希望main线程结束后子线程自动结束,需要把子线程设置为守护线程

        for (int i = 0; i < 10; i++) {
            System.out.println("你不正常");
            Thread.sleep(1000);
        }

        for (int i = 0; i < 10; i++) {
            System.out.println("我是正常人");
        }

    }
}
class MyDaemonThread implements Runnable{
    @Override
    public void run() {
        for (; ; ) {
            System.out.println("我是波波哈哈哈");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

卖票不超卖:休眠放到  run方法中

synchronized
package com.hspedu.ticket;


import com.hspedu.threaduse.ThreadUse02;

/**
 * @author 唐波~
 * @version 1.0
 */
public class SaleTicket {
    public static void main(String[] args) {
        SellTicket02 sellTicket02 = new SellTicket02();
        Thread thread1 = new Thread(sellTicket02);
        Thread thread2 = new Thread(sellTicket02);
        Thread thread3 = new Thread(sellTicket02);
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class  SellTicket02 implements Runnable {
    private  int num = 100;
    private boolean loop=true;
    public synchronized void m(){
        if (num <= 0) {
            System.out.println("票卖完了");
            loop=false;
            return;
        }

        System.out.println("窗口" + Thread.currentThread().getName() + "卖出了一张票" + "还有" + (--num) + "张票");
        System.out.println();
    }

    @Override
    public    void run() {
        while(loop){
            m();
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

或者在代码块加锁:尽量选择同步代码块加锁

public void m() {
    synchronized(this) {
        if (num <= 0) {
            System.out.println("票卖完了");
            loop = false;
            return;
        }

        System.out.println("窗口" + Thread.currentThread().getName() + "卖出了一张票" + "还有" + (--num) + "张票");
        System.out.println();
    }

 用Q或者q让线程退出:

线程B控制线程A退出

package com.hspedu.homework;

import javax.swing.*;
import java.awt.*;
import java.util.Scanner;

/**
 * @author 唐波~
 * @version 1.0
 */
public class HomeWork01 {
    public static void main(String[] args) {
        A a = new A();
        B b = new B(a);
        Thread thread=new Thread(a);
        Thread thread2=new Thread(b);
        thread.start();
        thread2.start();
    }
}
class A extends JPanel implements Runnable{
    private boolean loop=true;
    @Override
    public void run() {
        while(loop){
            System.out.println((int)(Math.random()*100)+1);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void setLoop(boolean loop) {
        this.loop = loop;
    }
}
class B extends JPanel implements Runnable {
    private A a;
    private Scanner scanner=new Scanner(System.in);

    public B(LayoutManager layout, boolean isDoubleBuffered, A a) {
        super(layout, isDoubleBuffered);
        this.a = a;
    }

    public B(LayoutManager layout, A a) {
        super(layout);
        this.a = a;
    }

    public B(boolean isDoubleBuffered, A a) {
        super(isDoubleBuffered);
        this.a = a;
    }


    public B(A a) {
        this.a = a;
    }

    public B() {

    }


    @Override
    public void run() {
        while (true) {
            System.out.println("请输入你的指令");
            char key=scanner.next().toUpperCase().charAt(0);
            if(key=='q'|key=='Q'){
               a.setLoop(false);
               break;
            }
        }
    }

}

取钱不能超取,用Runnable和syn:

package com.hspedu.homework;

import java.util.Scanner;

/**
 * @author 唐波~
 * @version 1.0
 */
public class QuMoney {
    public static void main(String[] args) {
        C c = new C();
        Thread thread = new Thread(c);
        Thread thread2 = new Thread(c);
        thread.start();
        thread2.start();
    }
}
class C implements Runnable{
    private static int money=1000;
    private Scanner scanner=new Scanner(System.in);

    @Override
    public synchronized void run() {
        while (true) {
            System.out.println("你要取多少钱" + "\n");
            int key=scanner.nextInt();
            if (money<key) {
                System.out.println("钱不够了");
                break;
            }
            if (money >= key) {
                System.out.println("取钱了" + key + "还剩" + (money -= key));
                
            }
        }
    }
}

创建文件的三种方式:

package com.hspedu.file01;

import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class File01 {
    public static void main(String[] args) {
    }
    @Test
    public void create01(){
        String filePath="F:\\测试文件\\news1.txt";
        File file=new File(filePath);
        try {
            file.createNewFile();//创建新文件
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式二:通过父目录+子路径
    @Test
    public void create02(){//这是还在内存里
        File parentFile=new File("F:\\测试文件");//文件夹名字
        String fileName="news2.txt";//文件名字

        File file = new File(parentFile, fileName);//父目录+子路径
        try {//创建新文件
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void create03(){
        String parentPath="F:\\测试文件";
        String filePath="new3.txt";
        File file = new File(parentPath, filePath);
        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

文件的常用方法:

package com.hspedu.file02;

import org.testng.annotations.Test;

import java.io.File;

/**
 * @author 唐波~
 * @version 1.0
 */
public class FileInformation {//获取文件信息
    public static void main(String[] args) {
    }
    @Test
    public void info(){
        File file = new File("F:\\测试文件\\news2.txt");
        //调用相应方法得到文件对应信息
        System.out.println("文件名字="+file.getName());
        System.out.println("文件的绝对路径为"+file.getAbsolutePath());
        System.out.println("文件的父级目录为"+file.getParent());
        System.out.println("文件的大小(字节)为"+file.length());
        System.out.println("文件是否存在"+file.exists());
        System.out.println("是个文件吗"+file.isFile());
        System.out.println("是目录吗"+file.isDirectory());


    }
}

创建和删除目录:多级目录创建:

package com.hspedu.directorys_;

import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Directory_ {
    public static void main(String[] args) {

    }
    @Test//判断文件是存在,存在就干掉
    public void m1(){//文件存在则删除,不存在则创建文件
        File file=new File("F:\\测试文件\\news1.txt");
        if(file.exists()){
            file.delete();
            System.out.println("文件已删除");
        }else {
            try {
                file.createNewFile();
                System.out.println("文件创建成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test//删除空文件夹    创建文件夹    file.mkdirs();
    public void m2(){
        File file=new File("F:\\测试文件\\ss\\bobo");
        if (file.exists()){
            file.delete();
            System.out.println("文件夹删除成功");
        }else {
            System.out.println("该目录不存在");
            file.mkdirs();
            System.out.println("创建了该文件夹");

        }
    }
}


FileInputStream 读取文件内容要注意的点:

1.一定要有finnally来释放资源:

finally {
    //关闭文件流,释放资源
    try {
        fileInputStream.close();
        System.out.println("\n文件流已经关闭,资源释放");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2.注意作用域:

3.注意FileInputStream的用法,-1代表已经到末尾了

while ((readData=fileInputStream.read())!=-1){
    System.out.print((char) readData);//转成char显示
}
FileInputStream fileInputStream=null;

4.有编译异常记得try//catch

package com.hspedu.inputstream;

import org.testng.annotations.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class FileInputStream_ {
    public static void main(String[] args) {

    }
    @Test
    public void readFile01(){
        String filePath="F:\\测试文件\\new3.txt";
        int readData=0;
        FileInputStream fileInputStream=null;
        //会有编译异常,记得try一下
        try {//创建File
            fileInputStream = new FileInputStream(filePath);

            while ((readData=fileInputStream.read())!=-1){
                System.out.print((char) readData);//转成char显示
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
                System.out.println("\n文件流已经关闭,资源释放");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

代码优化:通过数组一次读取多个字符提高效率:

package com.hspedu.inputstream;

import org.testng.annotations.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class FileInputStream03 {
    public static void main(String[] args) {
    }
    //使用read(byte[] b)进行代码优化,提高效率
    String filePtah2="F:\\测试文件\\new3.txt";
    FileInputStream fileInputStream=null;
    
    int readLength=0;//读取长度
    byte[] buf=new byte[8];定义字节数组一次读取八个字节
    @Test
    public void readFile(){
        try {
            fileInputStream=new FileInputStream(filePtah2);
            //如果读取正常返回实际的字节数,如果读取-1代表读取完毕
            while(((readLength=fileInputStream.read(buf))!=-1)){
                System.out.print(new String(buf,0,readLength));//利用String的构造器
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

在文件中写入内容:OutputStream:

细节1:加true代表追加,不加true则代表覆盖

fileOutputStream = new FileOutputStream(path,true);

细节2:一个加入多个字符用数组:str.getBytes还能设置格式

String str="hello  hsp";//遍历写入一个数组
fileOutputStream.write(str.getBytes(StandardCharsets.UTF_8));
package com.hspedu.outputstream_;

import org.testng.annotations.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author 唐波~
 * @version 1.0
 */
public class OutputStream1 {
    public static void main(String[] args) {
    }

    String path="F:\\测试文件\\news4.txt";
    @Test
    public void writeFile(){//将数据写入到文件中,不存在则创建
        FileOutputStream fileOutputStream=null;
        try {//这里true代表追加
            fileOutputStream = new FileOutputStream(path,true);
            fileOutputStream.write('a');//写入一个字节

            String str="hello  hsp";//遍历写入一个数组
            fileOutputStream.write(str.getBytes(StandardCharsets.UTF_8));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

文件拷贝:

package com.hspedu.filecopy_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class FileCopy1 {
    public static void main(String[] args) {
        //拷贝文件思路分析
        //1.创建文件的输入流,将文件读入到程序
        //2.创建文件的输出流,将读取到的文件数据,写入到指定的路径
        String srcPath="F:\\测试文件\\news4.txt";//源文件地址
        String destPath="F:\\测试文件\\news42.txt";//目标文件地址
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;

        try {
            fileInputStream=new FileInputStream(srcPath);
            fileOutputStream=new FileOutputStream(destPath);
            //定义字节数组提高效率
            byte[] buf =new byte[1024];
            int readLength=0;
            try {
                while((fileInputStream.read(buf))!=-1){
                    System.out.println(new String(buf,0,readLength));
                    //读取一部分就写入到文件
                    //!!!!一定要用这个方法!!!!不然还没读完呢
                    fileOutputStream.write(buf,0,readLength);//一定要用这个方法
                }
                System.out.println("拷贝成功OKK");
            } catch (IOException e) {
                e.printStackTrace();
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileInputStream!=null) {
                    fileInputStream.close();
                }if (fileOutputStream!=null) {
                    fileOutputStream.close();
                }
                System.out.println("关闭输入输出流,释放资源");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}

读取文件内容:数组,好用@!!

package com.hspedu.reader_;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Reader_ {
    public static void main(String[] args) {
        //先创建FileReader对象
        FileReader fileReader=null;
        String filePath="F:\\测试文件\\story1.txt";
        int readLength=0;
        char[] buf=new char[1024];
        try {//读取文档内容
            fileReader = new FileReader(filePath);
            while((readLength=fileReader.read(buf))!=-1){
                //把数组里的取出来转成字符串
                System.out.print(new String(buf,0,readLength));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileReader!=null){
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

FileWritter写入文件:

                                    这个true很关键,决定是追加还是覆盖///

fileWriter = new FileWriter(path2,true);

1.细节且重要,!!!!!一定要关流!!!!!否则事情白干了,可能会造成巨大损失

package com.hspedu.writer_;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class FileWriter_ {
    public static void main(String[] args) {
        String path2="F:\\测试文件\\story1.txt";
        FileWriter fileWriter =null;
        //创建一个FileWriter对象
        try {
            fileWriter = new FileWriter(path2,true);
            fileWriter.write("hhhh");
            System.out.println("成功写入");

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

FileWritter数组写入:

数组写入很方便

package com.hspedu.writer_;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class FileWriter_ {
    public static void main(String[] args) {
        String path2="F:\\测试文件\\story1.txt";
        FileWriter fileWriter =null;
//        char[] chars={'a','b','c'};
        String[] strings={"'a','b','c'"};

        //创建一个FileWriter对象
        try {
            fileWriter = new FileWriter(path2,true);
            fileWriter.write("hhhh");
            for (int i = 0; i < strings.length; i++) {
                System.out.println(strings);
//                fileWriter.write(chars[i]);
                fileWriter.write(strings[i]);
                fileWriter.write("韩顺平教育".toCharArray(),0,3);
                fileWriter.write("韩顺平教育哈哈哈");
                fileWriter.write("韩顺平教育".toCharArray(), 0, 3);
                fileWriter.write("韩顺平教育哈哈哈");
                fileWriter.write("上海田径场", 0, 2);
            }
            System.out.println("成功写入");

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

BufferedReader按行读取文本内容:

package com.hspedu.reader_;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class BufferedReader_ {
    public static void main(String[] args) {
        String path="F:\\测试文件\\story1.txt";
        BufferedReader bufferedReader=null;
        String line;
        try {//在bufferedReader新创建一个FileReader;
            bufferedReader = new BufferedReader(new FileReader(path));
            line=bufferedReader.readLine();//按行读取,返回为空时表示读取完毕
            while (line!=null){
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();//底层会自动关闭节点利于
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

l利用BufferWriter写入数据到文件:

        bufferedWriter = new BufferedWriter(new FileWriter(path));

package com.hspedu.reader_;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
//通过BufferWriter写入文件,会自动创建文件
public class BufferWriter_ {
    public static void main(String[] args) {
        String path="F:\\测试文件\\story2.txt ";
        BufferedWriter bufferedWriter =null;
        String str="hadshjsafdhjsagdhj";
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(path));
            bufferedWriter.write(str);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(bufferedWriter!=null) {
                    System.out.println("文件写入成功");
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

java_Buffered拷贝:

别忘了写进去,否则是个空文件

package com.hspedu.reader_;

import java.io.*;

/**
 * @author 唐波~
 * @version 1.0
 */
public class BufferCopy {
    public static void main(String[] args)  {
        String startFile="F:\\测试文件\\story2.txt";
        String endFile="F:\\测试文件\\story2copy.txt";
        BufferedReader bufferedReader =null;
        BufferedWriter bufferedWriter =null;
        String line1;

        try {
            bufferedReader = new BufferedReader(new FileReader(startFile));
            bufferedWriter = new BufferedWriter(new FileWriter(endFile));
            while((line1= bufferedReader.readLine())!=null){//读取文件内容,每读一行写一行
                bufferedWriter.write(line1);//写进去
                bufferedWriter.newLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
好好看好好学
拷贝拷贝东西都靠这个
BufferedInputStream和BufferedOutputStream拷贝二进制文件:音频视频,图片

好好看好好学//文件处理流

package com.hspedu.bufferedInputstream_;

import java.io.*;

/**
 * @author 唐波~
 * @version 1.0
 */
public class BufferedInputStream01 {
    public static void main(String[] args) {
        String startFile="F:\\测试文件\\black2_2x.jpg!0x0.webp";
        String endFile="F:\\测试文件\\3.png";
        BufferedInputStream bufferedInputStream1=null;
        BufferedOutputStream  bufferedOutputStream2 =null;

        //二进制读取文件,好好学好好看
        try {
            bufferedInputStream1=new BufferedInputStream(new FileInputStream(startFile));
            bufferedOutputStream2=new BufferedOutputStream(new FileOutputStream(endFile));
            byte[] buff=new byte[1024];
            int readLength=0;

            while ((readLength=bufferedInputStream1.read(buff))!=-1){
                //二进制读取文件,好好学好好看.拷贝音频视频
                bufferedOutputStream2.write(buff,0,readLength);
            }
            System.out.println("文件拷贝完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {if(bufferedInputStream1!=null) {
                bufferedInputStream1.close();
            }if(bufferedOutputStream2!=null){
                bufferedOutputStream2.close();
                System.out.println("拷贝了");
            }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
保存对象(序列化):

            objectOutputStream.writeObject(new Dog("旺财",1));
            objectOutputStream.close();
            System.out.println("对象数据保存完毕(序列化)");

class Dog implements Serializable {//s实现Serializable接口
    private String name;
    private int age;

只是版本升级加这个

private String hobby;
private static final long serialVersionUID=1L;

package com.hspedu.outputstream_;

import org.yaml.snakeyaml.serializer.Serializer;
import org.yaml.snakeyaml.serializer.SerializerException;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ObjectOutStream_ {
    public static void main(String[] args) {
        String endFile="F:\\测试文件\\ObjectOutputStream.png";
        //序列化后保存不是纯文本的,而是按照他自己的格式
        ObjectOutputStream objectOutputStream =null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(endFile));

            objectOutputStream.write(100);//int在底层会自动装箱成-->>Integer实现了Serializable
            objectOutputStream.writeBoolean(true);//也会自动装箱
            objectOutputStream.writeChar('A');//char-->>Character
            objectOutputStream.writeDouble(9.7);
            objectOutputStream.writeUTF("韩顺平");//保存字符串


            objectOutputStream.writeObject(new Dog("旺财",1));
            objectOutputStream.close();
            System.out.println("对象数据保存完毕(序列化)");


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

    }
}
class Dog implements Serializable {//s实现Serializable接口
    private String name;
    private int age;


    public Dog(String name,int age) {
        this.age = age;
        this.name = name;
    }
}

反序列化恢复对象:

只能按照顺序恢复,对象是个类,,还要把类放到可以引用的位置

            //怎么恢复对象
            Object dog=objectInputStream.readObject();
            System.out.println(dog);
 

package com.hspedu.inputstream;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ObjectInputStream_ {
    public static void main(String[] args) {
        String endFile="F:\\测试文件\\ObjectOutputStream.png";
        ObjectInputStream objectInputStream =null;

        try {
            objectInputStream = new ObjectInputStream(new FileInputStream(endFile));
            //读取顺序要和保存顺序一样
            System.out.println(objectInputStream.readInt());
            System.out.println(objectInputStream.readBoolean());
            System.out.println(objectInputStream.readChar());
            System.out.println(objectInputStream.readDouble());
            System.out.println(objectInputStream.readUTF());

            //怎么恢复对象
            Object dog=objectInputStream.readObject();
            System.out.println(dog);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                objectInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

指定编码输出文件内容,防止乱码:

* 将字节流FileInputStream转换成字符流InputStreamReader,指定编码UTF-8
package com.hspedu.transformation_;

import java.io.*;

/**
 * @author 唐波~
 * @version 1.0
 * 将字节流FileInputStream转换成字符流InputStreamReader,指定编码gbk
 */
public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String path="F:\\测试文件\\测试文件2\\a.txt";
        //将字节流FileInputStream转换成字符流InputStreamReader
        //同时指定编码,最终要BufferReader读取
        InputStreamReader gbk = new InputStreamReader(new FileInputStream(path), "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(gbk);
        //程序员下面这么写
        // BufferedReader gbk = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
        //4.读取
        String str=bufferedReader.readLine();
        System.out.println(str);
        //5.gua关流
        gbk.close();

    }
}

zz字节流转换2:

package com.hspedu.transformation_;

import java.io.*;

/**
 * @author 唐波~
 * @version 1.0
 * * 将字节流FileOutputStream转换成字符流OutputStreamWriter,指定编码gbk
 */
public class OutputStreamWriter_ {
    public static void main(String[] args) {
        String path="F:\\测试文件\\测试文件2\\a1.txt";
        OutputStreamWriter osw =null;
        try {
            osw = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");
            try {
                osw.write("hi,韩顺平教育");
                System.out.println("保存成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
修改打印流的设备:输出内容到文件:
package com.hspedu.printstream_;

import java.io.FileNotFoundException;
import java.io.PrintStream;

/**
 * @author 唐波~
 * @version 1.0
 */
public class PrintStream_ {
    public static void main(String[] args) {
        //默认打印  在显示器    可以修改
        PrintStream out=System.out;
        out.println("he  john");
        //==out.write("he  john".getBytes())//看源码就知道了,println底层是write
        out.close();

        //修改打印流的设备:输出内容到文件
        //private static native void setOut0(PrintStream out);
        try {
            System.setOut(new PrintStream("F:\\测试文件\\t1.txt"));
            System.out.println("hello  韩顺平");//输出内容到文件


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }
}

打印流2:输出到文件

package com.hspedu.printwriter_;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 唐波~
 * @version 1.0
 */
public class PrintWriter_ {
    public static void main(String[] args) {
        //PrintWriter printWriter = new PrintWriter(System.out);
        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter(new FileWriter("F:\\测试文件\\t2.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        printWriter.println("hi  北京");
        printWriter.close();//一定要有得动作
    }
}

 //使用Properties来读取mysql.properties的键值对

package com.hspedu.properties02;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Properties02 {
    public static void main(String[] args) throws IOException {
        //使用Properties来读取mysql.properties的键值对

        Properties properties = new Properties();
        //1.创建Properties对象
        //2.读取文件
        //3.显示键值对到控制台
        //4.根据key获取对应的值
        properties.load(new FileReader("src\\mysql.properties"));
        properties.list(System.out);
        String name = properties.getProperty("name");
        System.out.println(name);
    }
}

写入键值对到配置文件

package com.hspedu.properties02;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Properties04 {
    public static void main(String[] args) {
        Properties properties = new Properties();
//        1.如果键值对不存在则创建,存在则修改
        properties.setProperty("charset","utf-8");
        properties.setProperty("username","张波");
//        FileOutputStream fileOutputStream=null;
        //将K---V存储在文件中
        try {
            properties.store(new FileOutputStream("src\\mysql2.properties"),null);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

判断文件是否存在,不存在则创建,并输入内容:

自己写的1.19

package com.hspedu.homework01;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 唐波~
 * @version 1.0
 */
public class MyTemp03 {
    public static void main(String[] args) {
        String path="E:\\mytemp";
        String path2=path+"\\hello.txt";
        String contents="\n小象叮叮叮";
        File file = new File(path);
        File file1 = new File(path2);
        if (!file.exists()){
            file.mkdirs();
            System.out.println("文件创建成功");
            if (file.exists()){
                try {
                    file1.createNewFile();
                    FileOutputStream fileOutputStream = new FileOutputStream(path2, true);
                    fileOutputStream.write(contents.getBytes(StandardCharsets.UTF_8));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            System.out.println("文件夹已经存在");
            try {
                file1.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(path2, true);
                fileOutputStream.write(contents.getBytes(StandardCharsets.UTF_8));
                System.out.println("写入内容成功");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

文件写入内容:

                FileOutputStream fileOutputStream = new FileOutputStream(path2, true);
                fileOutputStream.write(content.getBytes(StandardCharsets.UTF_8));

package com.hspedu.homework01;

import jdk.swing.interop.SwingInterOpUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 唐波~
 * @version 1.0
 */
public class MyTemp04 {
    public static void main(String[] args) throws IOException {
        String path="e:mytemp2";
        String path2=path+"\\bobo.txt";
        String content="我是波波";
        File file = new File(path);
        File file1 = new File(path2);
        if (!file.exists()){
            file.mkdirs();
            System.out.println("已创建文件夹"+path);
            if (file.exists()){
                file1.createNewFile();
                System.out.println("已创建文件"+path2);
                FileOutputStream fileOutputStream = new FileOutputStream(path2, true);
                fileOutputStream.write(content.getBytes(StandardCharsets.UTF_8));
                System.out.println("文件内容已追加写入");
            }
        }else {
            if(!file1.exists()){
                file1.createNewFile();
                System.out.println("已创建文件"+path2);
                FileOutputStream fileOutputStream = new FileOutputStream(path2, true);
                fileOutputStream.write(content.getBytes(StandardCharsets.UTF_8));
                System.out.println("文件内容已追加写入");
            }else {
                System.out.println("文件"+path2+"已存在");
            }
        }
    }
}

打印文件内容,并在前面加行号:

package com.hspedu.homework01;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class BufferReader02 {
    public static void main(String[] args)  {
        String path="F:\\测试文件\\bobo.txt";
        BufferedReader bufferedReader =null;
        int temp=0;
        String line= null;
        try {
            line = " ";
            bufferedReader = new BufferedReader(new FileReader(path));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            while((line=bufferedReader.readLine())!=null){
                System.out.println(++temp+" "+line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(line!=null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

s

序列化必须实现串口化:

class Dog4 implements Serializable {
}

读取键值对内容并输出

保存对象到文件中

package com.hspedu.newdog;

import java.io.*;
import java.util.Properties;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Dog3 {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            properties.load(new FileReader("D:\\idea_java_projects\\chapter19\\src\\dog.properties"));
            properties.list(System.out);

            String name = properties.get("name")+" ";//类型的转换
            int age = Integer.parseInt(properties.get("age")+"");
            String color=properties.get("color")+" ";

            Dog4 dog = new Dog4(name, age, color);
            System.out.println(dog);

            String path="F:\\测试文件\\测试文件2\\b.txt";
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path));
            objectOutputStream.writeObject(dog);
            objectOutputStream.close();//dog对象的序列化完成


        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }

    }
}
class Dog4 implements Serializable {
    private String name;
    private int age;
    private String color;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

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

    @Override
    public String toString() {
        return "Dog4{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }

    public Dog4(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }
}

t通过程序获得本机和服务器的名字和ip

InetAddress的使用
package com.hspedu.api;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author 唐波~
 * @version 1.0
 */
public class API_ {
    public static void main(String[] args) throws UnknownHostException {
        //InetAddress
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost);

        InetAddress bobo = InetAddress.getByName("波波");
        System.out.println(bobo);

        //3根据域名返回
        InetAddress allByName = InetAddress.getByName("www.baidu.com");
        System.out.println(allByName);

        String hostAddress = allByName.getHostAddress();
        //对应的主机地址
        System.out.println(hostAddress);
        System.out.println(bobo.getHostAddress());
        //主机名或者域名
        System.out.println(bobo.getHostName());
    }
}

TCP编程:

服务器端:

package com.hspedu.socket01;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 唐波~
 * @version 1.0
 * 服务端
 */
public class SocketTCP01Server {
    public static void main(String[] args) throws IOException {
        //1.在本机的9999端口监听,等待连接
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端口监听等待连接");
        //2,当没有9999端口时程序会阻塞,等待连接
        //如果有客户端连接则会返回socket对象
        Socket socket = serverSocket.accept();
        System.out.println("服务器端socket="+socket.getClass());

        //3通过socket来获取输入流
        InputStream inputStream = socket.getInputStream();
        //4.IO读取
        byte[] buf =new byte[1024];
        int readlen=0;
        while ((readlen=(inputStream.read(buf)))!=-1) {
            System.out.println(new String(buf, 0, readlen));
        }
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}

客户端输入内容:

在服务器端输出:

package com.hspedu.socket01;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * @author 唐波~
 * @version 1.0
 */
public class SocketTCP01Client {
    public static void main(String[] args) throws IOException {
        //连接这台主机的9999端口,如果连接成功返回socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(),9999);
        System.out.println("客户端socket="+socket.getClass());
        //连接上后,生成Socket,
        //通过socket.getOutputStream()得到和socket对象关联的输出流
        OutputStream outputStream = socket.getOutputStream();
        //3.通过输入流,写入数据到数据通道
        outputStream.write("hello,server".getBytes(StandardCharsets.UTF_8));
        //关闭流
        outputStream.close();
        socket.close();
        System.out.println("客户端退出");
    }
}

上次握手,服务器和客户端的的互相发送:

服务器端:记得关流,两端都要关

package com.hspedu.socket03;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Server03 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("在监听9999端口\n");
        Socket accept = serverSocket.accept();
        System.out.println("监听成功");

        byte[] bytes=new byte[1024];
        int readlen=0;
        InputStream inputStream = accept.getInputStream();
        while((readlen=(inputStream.read(bytes)))!=-1){
            System.out.println(new String(bytes,0,readlen));
        }
        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("我也是波波".getBytes(StandardCharsets.UTF_8));
        accept.shutdownOutput();//结束输出

        inputStream.close();
        outputStream.close();
        inputStream.close();
        accept.close();
        serverSocket.close();
    }
}

客户端:

package com.hspedu.socket03;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Client03 {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println(socket.getClass());

        //准备写入数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("我是波波".getBytes(StandardCharsets.UTF_8));
        socket.shutdownOutput();//结束输出
        System.out.println("字符串已写入");

        byte[] bytes=new byte[1024];
        int readlen=0;
        InputStream inputStream = socket.getInputStream();

        while ((readlen=inputStream.read(bytes))!=-1){
            System.out.println(new String(bytes,0,readlen));
        }

        inputStream.close();
        socket.close();
        outputStream.close();

    }
}

字符流服务器server:

package com.hspedu.socket03;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Server03 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("在监听9999端口\n");
        Socket accept = serverSocket.accept();
        System.out.println("监听成功");

//        byte[] bytes=new byte[1024];
//        int readlen=0;
       InputStream inputStream = accept.getInputStream();
//        while((readlen=(inputStream.read(bytes)))!=-1){
//            System.out.println(new String(bytes,0,readlen));
//        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);

        OutputStream outputStream = accept.getOutputStream();
//        outputStream.write("我也是波波".getBytes(StandardCharsets.UTF_8));
//        accept.shutdownOutput();//结束输出
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello client字符流");
        bufferedWriter.flush();


        bufferedReader.close();
        bufferedWriter.close();
        inputStream.close();
        outputStream.close();
        inputStream.close();
        accept.close();
        serverSocket.close();
    }
}

z字符流客户端

package com.hspedu.socket03;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * @author 唐波~
 * @version 1.0
 */
public class Client03 {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println(socket.getClass());

        //准备写入数据
        OutputStream outputStream = socket.getOutputStream();
//        outputStream.write("我是波波".getBytes(StandardCharsets.UTF_8));
//        socket.shutdownOutput();//结束输出
//        System.out.println("字符串已写入");
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("我是波波哈哈哈哈");
        bufferedWriter.newLine();//插入一个换行符,表示写入内容结束
        bufferedWriter.flush();

//        byte[] bytes=new byte[1024];
//        int readlen=0;
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);
//        while ((readlen=inputStream.read(bytes))!=-1){
//            System.out.println(new String(bytes,0,readlen));
//        }

        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
        outputStream.close();

    }
}

读取配置文件和反射入门:

package com.hspedu.reflection.question;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @author 唐波~
 * @version 1.0
 */
public class ReflectionQuestion {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Cat cat = new Cat();
        cat.hi();

        Properties properties = new Properties();
        properties.load(new FileInputStream("D:\\idea_java_projects\\chapter23\\src\\re.properties"));
        String classfullpath = properties.get("classfullpath").toString();
        String method = properties.get(("method")).toString();
        System.out.println(classfullpath);
        System.out.println(method);


        //反射机制
        //1.加载类
        Class cls = Class.forName(classfullpath);
        //2通过cls得到类加载的对象实例
        Object o = cls.newInstance();
        //3得到方法名
        Method method1 = cls.getMethod(method);
        //4调用
        System.out.println("=========================================");
        method1.invoke(o);

    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apache Thrift 是一种高效且跨语言的远程服务调用框架,它可以让你使用不同的编程语言实现客户端和服务器端,并且在它们之间进行通信。下面是使用 Java 快速入门 Apache Thrift 的步骤: 1. 安装 Thrift 首先,你需要从 Apache Thrift 的官方网站(https://thrift.apache.org/)下载并安装 Thrift。 2. 定义接口文件 在 Thrift 中,你需要定义一个接口文件,它描述了你的服务接口和数据类型。下面是一个简单的示例: ``` namespace java com.example service MyService { string sayHello(1: string name) } ``` 上面的代码定义了一个名为 MyService 的服务,它有一个名为 sayHello 的方法,它接受一个名为 name 的字符串参数,并返回一个字符串。 3. 生成代码 使用 Thrift 编译器(thrift)来生成 Java 代码: ``` thrift --gen java MyService.thrift ``` 这将生成一个名为 MyService.javaJava 接口文件,以及一些用于序列化和反序列化的辅助类。 4. 实现服务 你需要编写一个实现 MyService 接口的 Java 类,例如: ``` public class MyServiceImpl implements MyService.Iface { public String sayHello(String name) throws TException { return "Hello, " + name + "!"; } } ``` 上面的代码实现了 sayHello 方法,并返回一个带有名称的问候语。 5. 启动服务器 你需要编写一个 Java 服务器,以便可以在其中运行 MyServiceImpl。以下是一个简单的示例: ``` public class MyServer { public static void main(String[] args) throws Exception { TServerTransport serverTransport = new TServerSocket(9090); TServer server = new TSimpleServer(new Args(serverTransport).processor(new MyService.Processor(new MyServiceImpl()))); System.out.println("Starting the server..."); server.serve(); } } ``` 上面的代码创建了一个 TSimpleServer 实例,并将其绑定到本地的 9090 端口。它还将 MyServiceImpl 的实例添加到 MyService.Processor 中,以便服务器可以调用 MyServiceImpl 中实现的方法。 6. 编写客户端 你需要编写一个 Java 客户端,以便可以调用 MyServiceImpl 中实现的方法。以下是一个简单的示例: ``` public class MyClient { public static void main(String[] args) throws Exception { TTransport transport = new TSocket("localhost", 9090); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); MyService.Client client = new MyService.Client(protocol); String result = client.sayHello("World"); System.out.println(result); transport.close(); } } ``` 上面的代码创建了一个 TSocket 实例,并将其连接到本地的 9090 端口。它还创建了一个 MyService.Client 实例,并使用它来调用 MyServiceImpl 中实现的 sayHello 方法。 以上就是使用 Java 快速入门 Apache Thrift 的步骤。你可以通过阅读 Thrift 的官方文档来了解更多信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值