Java SE基础编程练习

最近开始重新学Java SE基础,打算把整理的笔记和练习的代码同步整理到博客上来。方便之后复习工具,也要把学到的内容及时用自己的语言输出出来,否则学得不够扎实容易理解不深刻,慢一点就是快一点。

1. 基础知识练习(分支、循环、数组、方法)

在这里插入图片描述

import java.util.Scanner;

public class BasicPractice {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int day = scanner.nextInt();
        if (day < 1 || day > 7) System.out.println("Wrong Input!Please enter a number between 1 and 7.");
        switch (day) {
            case 1:
                System.out.println("跑步");
                break;

            case 2:
                System.out.println("游泳");
                break;

            case 3:
                System.out.println("慢走");
                break;

            case 4:
                System.out.println("动感单车");
                break;

            case 5:
                System.out.println("拳击");
                break;

            case 6:
                System.out.println("爬山");
                break;

            case 7:
                System.out.println("好好吃一顿");
                break;
        }
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) {
        for (int x=1;x<101;x++){
            if (x % 10 == 7 || x / 10 % 10 == 7 || x % 7 == 0) {
                System.out.print(x + ",");
            }
        }
    }
}

注意int和单个字符的字符串连接时,千万不能把双引号改写成单引号,比如上例中如果改写为x+’,’,char类型会向上转型为int类型,也就是逗号的底层数值和x相加,得到一个不正确的值。
在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) {
        int[] rabbit = new int[20]; // 数组的动态初始化,指定数组长度,不指定会编译报错
        rabbit[0] = 1;
        rabbit[1] = 1;
        for (int i=2;i<20;i++){
            rabbit[i] = rabbit[i-1] + rabbit[i-2];
        }
        System.out.println(rabbit[19]);
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) {
       for (int x=0;x<=20;x++){
           for (int y=0;y<=33;y++){
               for (int k=0;k<=100;k++)
               {
                   System.out.println(x+","+y+","+k);
               }
           }
       }
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) {
       int[] arr = {68,27,95,88,171,996,51,210};
       int sum = 0;
       for (int x:arr){
           if (x%10 !=7 && x/10%10!=7 && x%2==0) sum += x;
       }
        System.out.println(sum);
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) {
    int[] a = {1,2,3,4,5};
    int[] b = {1,2,3,4,5};
    boolean same = compareArray(a,b);
    System.out.println(same);
    }
    // 必须标记成静态方法,因为main是静态方法,静态方法只能调用静态方法
    public static boolean compareArray(int[] a, int[] b){
        if (a.length != b.length) return false;
        for (int i=0;i<a.length;i++){
            if (a[i]!=b[i]) return false;
        }
        return true;
    }
}

在这里插入图片描述

import java.util.Scanner;

public class BasicPractice {
    public static void main(String[] args) {
    int[] a = {19,28,37,46,50};
    Scanner scanner = new Scanner(System.in);
    int b = scanner.nextInt();
    int same = compareArray(a,b);
    System.out.println(same);
    }
    // 必须标记成静态方法,因为main是静态方法,静态方法只能调用静态方法
    public static int compareArray(int[] a, int b){
        for (int i=0;i<a.length;i++){
            if (a[i]==b) return i;
        }
        return -1;
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) {
    int[] a = {19,28,37,46,50};
    reverse(a);
    for (int i:a) System.out.print(i + ",");
    }
    // 必须标记成静态方法,因为main是静态方法,静态方法只能调用静态方法
    public static void reverse(int[] a){
        int tmp;
        for (int i=0;i<a.length/2+1;i++){
            tmp = a[i];
            a[i] = a[a.length-i-1];
            a[a.length-i-1] = tmp;
        }
    }
}

在这里插入图片描述

import java.util.Scanner;

public class BasicPractice {
    public static void main(String[] args) {
    int[] a = new int[6];
    Scanner scanner = new Scanner(System.in);
    int count = a.length;
    while (count > 0){
        count--;
        a[count] = scanner.nextInt();
    }
    max_min_sum(a);
    }
    // 必须标记成静态方法,因为main是静态方法,静态方法只能调用静态方法
    public static void max_min_sum(int[] a){
        int minScore = 100;
        int maxScore = 0;
        int sum = 0;
        for (int i=0;i<a.length;i++){
            if (a[i] < minScore) minScore = a[i];
            if (a[i] > maxScore) maxScore = a[i];
            sum += a[i];
        }
        System.out.println(minScore + "," + maxScore + "," + sum);
    }
}

2. 集合基础

在这里插入图片描述

import java.util.ArrayList;
import java.util.Scanner;

public class BasicPractice {
    public static void main(String[] args) {
        ArrayList<String> al = new ArrayList<>();
        al.add("hello");
        al.add("world");
        al.add("java");

        for (int i=0;i<al.size();i++){
            String s = al.get(i);
            System.out.println(s);
        }
    }

}

在这里插入图片描述

import java.util.ArrayList;
import java.util.Scanner;

public class BasicPractice {
    public static void main(String[] args) {
        ArrayList<Student> al = new ArrayList<>();
        Student stu1 = new Student("niumeng", 20);
        Student stu2 = new Student("niumeng2", 21);
        Student stu3 = new Student("niumeng3", 22);

        al.add(stu1);
        al.add(stu2);
        al.add(stu3);

        for (Student stu : al){
            System.out.println(stu.getName() + "," + stu.getAge());
        }
    }

}

在这里插入图片描述

  • Scanner中next()和nextLine()的区别:next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next方法会自动将其去掉,只有在输入有效字符之后,next方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。而nextLine是遇到回车是才结束,所以可以得到带空格的字符串,如果先读取了一个nextInt,后面紧跟着一个nextLine,此时的nextLine会接收nextInt中未接收的\r换行符而结束输入,需要下面再跟着一个nextLine才能接收到想接收的字符串。
import java.util.ArrayList;
import java.util.Scanner;

public class BasicPractice {
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>(); // database
        while (true) {
            System.out.println("----------welcome----------");
            System.out.println("1. add student");
            System.out.println("2. delete student");
            System.out.println("3. modify student");
            System.out.println("4. check student");
            System.out.println("5. exit");
            System.out.println("please enter your choice(1-5)");
            Scanner scanner = new Scanner(System.in);
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    addStu(students);
                    break;
                case 2:
                    delStu(students);
                    break;
                case 3:
                    modStu(students);
                    break;
                case 4:
                    checkStu(students);
                    break;
                case 5:
                    System.out.println("谢谢使用");
                    return;
            }
        }
    }

    public static void addStu(ArrayList<Student> arrayList){
        Scanner s = new Scanner(System.in);
        System.out.println("学号:");
        String sid = s.next();
        System.out.println("姓名:");
        String name = s.next();
        System.out.println("年龄:");
        int age = s.nextInt();
        System.out.println("地址:");
        String address = s.next();
        Student student = new Student(name, age, address, sid);
        arrayList.add(student);
        System.out.println("add student over..");
    }

    public static void delStu(ArrayList<Student> arrayList){
        System.out.println("请输入你要删除的学生学号");
        Scanner s = new Scanner(System.in);
        String sid = s.nextLine();
        int tmp = -1;
        for (int i=0;i<arrayList.size();i++){
            if (arrayList.get(i).getSid().equals(sid)) tmp = i;
        }
        arrayList.remove(tmp);
        System.out.println("删除成功!");

    }
    public static void modStu(ArrayList<Student> arrayList){
        Scanner s = new Scanner(System.in);
        System.out.println("请输入你要修改的学生学号:");
        String sid = s.next();
        System.out.println("新姓名:");
        String name = s.next();
        System.out.println("新年龄:");
        int age = s.nextInt();
        System.out.println("新地址:");
        String address = s.next();
        for (int i=0;i<arrayList.size();i++){
            if (arrayList.get(i).getSid().equals(sid)){
                arrayList.set(i,new Student(name, age, address, sid));
            }
        }

    }

    public static void checkStu(ArrayList<Student> arrayList){
        if (arrayList.size() == 0)
            System.out.println("没有数据,请先添加学生信息");
        else {
            System.out.println("学号     姓名     年龄    地址");
            for (Student stu : arrayList) {
                System.out.println(stu.getSid() + "     " + stu.getName() + "     " + stu.getAge() + "     " + stu.getAddress());
            }
        }
    }


}

3. 面向对象

在这里插入图片描述

public class Cat extends Animal{
    public Cat(String name, String age) {
        super(name, age);
    }

    public Cat() {
        super();
    }

    @Override
    public void eat(){
        System.out.println("CAT eat fish");
    }
}
package com.practice;

public class Animal {
    private String name;
    private String age;

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

    public Animal() {
    }

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

    public void eat(){
        System.out.println("Animal need eat");
    }
}

public class BasicPractice {
    public static void main(String[] args) {
    Animal a = new Cat("NM", "2");
    a.eat();
    }
}

在这里插入图片描述

package com.practice;

public abstract class Animal {
    private String name;
    private String age;

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

    public Animal() {
    }

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

    public abstract void eat();
}

  • Animal中的eat方法本身就不会被调用,定义为抽象类时,eat方法只是规定了一个模板。抽象类中也可以定义非抽象的方法和属性,这样方便直接继承。

在这里插入图片描述

public interface SpeachEnglish {
    void speakEnglish();
}

import java.util.Collections;

public class BasketBallCoach extends Coach implements SpeachEnglish{
    public BasketBallCoach(String name, int age) {
        super(name, age);
    }

    public BasketBallCoach() {
        super();
    }

    @Override
    public void teach() {
        System.out.println("basketball coach teaches basketball");
    }

    @Override
    public void eat() {
        System.out.println("basketball coach eat");
    }

    @Override
    public void speakEnglish() {
        System.out.println("I can speak english");
    }
}
  • 接口是当抽象类中的成员方法均为抽象方法时,抽象类直接转型为接口,一个接口中只定义了实现类应该做的模板,而没有具体的实现方法。并且接口还可以多实现,满足了抽象类不能多继承的缺点。

匿名内部类:

public class BasicPractice {
    public static void main(String[] args) {
        SpeakEngOperator so = new SpeakEngOperator();
        so.method(new SpeachEnglish() {
            @Override
            public void speakEnglish() {
                System.out.println("I speak english");
            }
        }); // 此时要传入一个SpeakEng接口的实现类对象,那还需要额外定义

        so.method(() -> System.out.println("I speak lambda"));
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) {
        String s = "91 27 46 38 50";
        String[] s1 = s.split(" ");
        int[] a = new int[5];
        for (int i=0;i<s1.length;i++){
            a[i] = Integer.parseInt(s1[i]);
        }
        Arrays.sort(a);
        StringBuilder res = new StringBuilder();
        for (int i=0;i<a.length;i++){
            res.append(a[i]+"   ");
        }
        System.out.println(res);
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        Date date = new Date();
        String pattern = "yyyy-MM-dd-HH-mm-ss";
        String s = DateUtils.dateToString(date, pattern);
        Date newd = DateUtils.StringToDate(s, pattern);

    }
}


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

public class DateUtils {
    public static String dateToString(Date date, String format){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        String f = simpleDateFormat.format(date);
        return f;
    }

    public static Date StringToDate(String s, String format) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date parse = simpleDateFormat.parse(s);
        return parse;
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        Scanner scanner = new Scanner(System.in);
        int year = scanner.nextInt();
        Calendar instance = Calendar.getInstance();
        instance.set(year, 2, 1);
        instance.add(Calendar.DATE, -1);

        int day = instance.get(Calendar.DATE);
        System.out.println(day);
    }
}

自定义异常类

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        Scanner scanner = new Scanner(System.in);
        int score = scanner.nextInt();
        Teacher teacher = new Teacher();
        try {
            teacher.checkScore(score);
        } catch (ScoreException e) {
            e.printStackTrace();
        }
        System.out.println("can i be excuted?");
    }
}

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        Collection<Student> students = new ArrayList<>();
        Student stu1 = new Student("nm", 20);
        Student stu2 = new Student("nm2", 20);
        Student stu3 = new Student("nm3", 20);
        students.add(stu1);
        students.add(stu2);
        students.add(stu3);
        Iterator<Student> it = students.iterator();
        while (it.hasNext()){
            Student next = it.next();
            System.out.println(next.getName() + "," + next.getAge());
        }
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        HashSet<Student> hs = new HashSet<>();
        Student stu1 = new Student("nm", 20);
        Student stu2 = new Student("nm2", 24);
        Student stu3 = new Student("nm", 20);
        hs.add(stu1);
        hs.add(stu2);
        System.out.println(stu1.hashCode());// 因为name和age相同,所以生成的哈希值相同
        System.out.println(stu3.hashCode());
        for (Student stu:hs){
            System.out.println(stu.getName() + "," + stu.getAge());
        }

    }
}

package com.practice;

import java.util.Objects;

public class Student{
    private String name;
    private int age;

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

    public Student() {
    }

    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 instanceof Student)) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age); // 为输入序列生成哈希值,如果name和age相同生成的hashcode相同
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        TreeSet<Student> hs = new TreeSet<>();
        Student stu1 = new Student("nm", 100);
        Student stu2 = new Student("wd2", 24);
        Student stu3 = new Student("abc", 24);
        hs.add(stu1);
        hs.add(stu2);
        hs.add(stu3);
        for (Student stu:hs){
            System.out.println(stu.getName() + "," + stu.getAge());
        }

    }
}

import java.util.Objects;

public class Student implements Comparable{
    private String name;
    private int age;

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

    public Student() {
    }

    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 instanceof Student)) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age); // 为输入序列生成哈希值,如果name和age相同生成的hashcode相同
    }

    @Override
    public int compareTo(Object o) {
        Student second = (Student)o;
        if (this.getAge() != second.getAge())
            return this.getAge() - second.getAge();
        else{
            return this.getName().compareTo(second.getName());
        }
//        return 0;
    }
}

// 或者使用comparator比较器
TreeSet<Student> hs = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num1 = o1.getAge() - o2.getAge();
                int num2 = num1==0?o1.getName().compareTo(o2.getName()):num1;
                return num2;
            }
        });

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        Random random = new Random();
        HashSet<Integer> hs = new HashSet<>();
        while(hs.size() < 10){
            int i = random.nextInt(21);
            hs.add(i);
        }
        for (int i:hs) System.out.println(i);

    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        HashMap<String, Student> hm = new HashMap<>();
        Student stu1 = new Student("nm", 21);
        Student stu2 = new Student("nm2", 22);
        hm.put("100", stu1);
        hm.put("101", stu2);
        for (String key:hm.keySet()){
            Student stu = hm.get(key);
            System.out.println(stu.getName() + ", " + stu.getAge());
        }
        for (Map.Entry<String, Student> entry:hm.entrySet()) {
            System.out.println(entry.getKey());
            Student stu = entry.getValue();
            System.out.println(stu.getName() + ", " + stu.getAge());
        }
    }
}

在这里插入图片描述
重写了equals和hashcode方法后,即使put了两次,最后遍历结合也只会打印一次。

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        HashMap<Student, String> hm = new HashMap<>();
        Student stu1 = new Student("nm", 21);
        Student stu2 = new Student("nm2", 22);
        Student stu3 = new Student("nm2", 22);
        hm.put(stu1, "liyuan7");
        hm.put(stu2, "liyuan8");
        hm.put(stu3, "liyuan8");
        for (Student stu:hm.keySet()){
            System.out.println(stu.getName() + ", " + stu.getAge());
        }

    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
//        Student stu1 = new Student("nm", 21);
//        Student stu2 = new Student("nm2", 22);
//        Student stu3 = new Student("nm2", 22);
        ArrayList<HashMap<String, String>> al = new ArrayList<>();
        HashMap<String, String> hm = new HashMap<>();
        hm.put("1", "liyuan7");
        hm.put("2", "liyuan8");
        hm.put("3", "liyuan8");
        al.add(hm);

        HashMap<String, String> hm2 = new HashMap<>();
        hm2.put("1", "liyuan7");
        hm2.put("2", "liyuan8");
        hm2.put("3", "liyuan8");
        al.add(hm2);

        for (HashMap<String, String> h:al){
            for (String key:h.keySet()) System.out.println(key + "," + h.get(key));
        }

    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.next();
        char[] chars = s.toCharArray();
        HashMap<Character, Integer> hm = new HashMap<>();

        for (int i=0;i<chars.length;i++){
            if (hm.containsKey(chars[i])){
                Integer count = hm.get(chars[i]);
                count++;
                hm.replace(chars[i], count);
            }
            else{
                hm.put(chars[i], 1);//第一次加入一个
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Character c:hm.keySet()){
            sb.append(c).append("(").append(hm.get(c)).append("),");
        }
        System.out.println(sb);

    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws ParseException {
        File file = new File("f:/itcast");
        getFiles(file);
    }

    public static void getFiles(File file){
        File[] files = file.listFiles();
        for (File f : files){
            if (f.isFile()){
                System.out.println(f.getAbsolutePath());
                return;
            }else{
                getFiles(f);
            }
        }
    }
}

IO

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        /*FileInputStream fi = new FileInputStream("f:/itcast/窗里窗外.txt");
        FileOutputStream fo = new FileOutputStream("idea_test/窗里窗外.txt");
        int by;
        while((by=fi.read())!=-1){
            fo.write(by);
        }
        fo.close();
        fi.close();*/
        FileOutputStream fo = new FileOutputStream("idea_test/test.txt");
        fo.write(97);
        fo.write("hello world".getBytes());
        fo.write("\r\n".getBytes());
        fo.write("no".getBytes());
        fo.close();

    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        FileInputStream fi = new FileInputStream("f:/itcast/mn.jpg");
        FileOutputStream fo = new FileOutputStream("idea_test/test.jpg");
        byte[] bytes = new byte[2048]; // byte是字节,Byte是包装类
        while(fi.read(bytes)!=-1)
        {
            fo.write(bytes);
        }
        fo.close();
        fi.close();
    }
}

每次读入一个字节数组,会比一个字节一个字节地读要快的多,byte数组相当于一个缓存,缓存存满了再往文件中写入。
字符缓冲流:

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        BufferedInputStream bi = new BufferedInputStream(new FileInputStream("f:/itcast/字节流复制图片.avi"));
        BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream("idea_test/字节流复制图片.avi"));
        byte[] b = new byte[2048];
        int len;
        while((len=bi.read(b))!=-1){
            bo.write(b,0,len);
        }
        bo.close();
        bi.close();
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws IOException {
//        ow.write("中国");
//        ow.close();
        InputStreamReader ir = new InputStreamReader(new FileInputStream("idea_test/BasketBallCoach.java"));
        OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream("idea_test/test.java"));

        int ch;
        while((ch=ir.read())!=-1){
            ow.write(ch);
        }
        ow.flush();
        ir.close();
    }
}

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        ArrayList<String> al = new ArrayList<>();
        al.add("hello");
        al.add("world");
        BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test/test.txt"));
        for (String s:al){
            bw.write(s);
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return (o1.getScore1()+o1.getScore2()+o1.getScore3()) - (o2.getScore1()+o2.getScore2()+o2.getScore3());
            }
        });

        ts.add(new Student("nm1", 85,76,95));
        ts.add(new Student("nm2", 55,96,85));
        ts.add(new Student("nm3", 65,56,75));

        BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test/test.txt"));
        for (Student s:ts){
            bw.write(s.toString());
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }

网络编程

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//从标准输入流中读取数据并用缓冲流类包装下
        String line;
        while(!(line=br.readLine()).equals("886")){
            byte[] bytes = line.getBytes();
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("127.0.0.1"), 8008);
            datagramSocket.send(datagramPacket);
        }
        datagramSocket.close();

    }
}

public class Receiver {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(8008);
        while(true) {
            byte[] b = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(b, b.length);
            datagramSocket.receive(datagramPacket);
            byte[] data = datagramPacket.getData();
            int length = datagramPacket.getLength();
            System.out.println(new String(data,0,length));
        }
    }
}

在这里插入图片描述
练习1:

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 8008);
        OutputStream outputStream = socket.getOutputStream();//获取到客户端的输出流,往输出流中写入数据
        outputStream.write("hello".getBytes());


        InputStream inputStream = socket.getInputStream();
        byte[] b = new byte[1024];
        int len=inputStream.read(b);
        System.out.println(new String(b, 0, len));
        socket.close();

    }
}

public class Receiver {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8008);
        Socket accept = serverSocket.accept();// 新建一个用于接收的socket对象,并获取输入流中的内容
        InputStream inputStream = accept.getInputStream();
        byte[] b = new byte[1024];
        int len=inputStream.read(b);
        System.out.println(new String(b, 0, len));
        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("received!".getBytes());
        serverSocket.close();
    }
}

  • 注意,一定要先开启服务端再开启客户端,否则在没有服务端开启的情况下发送TCP数据会报错的。
    练习2:
public class BasicPractice {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 8008);
        OutputStream outputStream = socket.getOutputStream();//获取到客户端的输出流,往输出流中写入数据
        // 打包的数据来源于键盘输出, 利用字符缓冲流的readline()功能读取数据 或者Scanner
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while(!(line=br.readLine()).equals("886")){
            outputStream.write(line.getBytes());
        }
        socket.close();

    }
}

public class Receiver {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8008);
        Socket accept = serverSocket.accept();// 新建一个用于接收的socket对象,并获取输入流中的内容
        InputStream inputStream = accept.getInputStream();
        byte[] b = new byte[1024];
        int len;
        while((len=inputStream.read(b))!=-1)
            System.out.println(new String(b, 0, len));

        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("received!".getBytes());
        serverSocket.close();
    }
}

练习3:

public class Receiver {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8008);
        Socket accept = serverSocket.accept();// 新建一个用于接收的socket对象,并获取输入流中的内容
        InputStream inputStream = accept.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test/test.txt"));
        String line;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        bw.close();
        serverSocket.close();
    }
}

在这里插入图片描述
练习4:

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 8008);
        OutputStream outputStream = socket.getOutputStream();//获取到客户端的输出流,往输出流中写入数据
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        // 打包的数据来源于键盘输出, 利用字符缓冲流的readline()功能读取数据 或者Scanner
        BufferedReader br = new BufferedReader(new FileReader("idea_test/窗里窗外.txt"));
        String line;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        bw.close();
        socket.close();

    }
}

练习5:这里需要用到shutdownoutputstream方法,否则客户端在等待服务端的反馈,服务端以为客户端可能还会有输入也迟迟没有走出循环,因此可以人为从客户端给出一个结束标志代表客户端传送数据结束了。

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 8008);
        OutputStream outputStream = socket.getOutputStream();//获取到客户端的输出流,往输出流中写入数据
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        // 打包的数据来源于键盘输出, 利用字符缓冲流的readline()功能读取数据 或者Scanner
        BufferedReader br = new BufferedReader(new FileReader("idea_test/BasketBallCoach.java"));
        String line;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        socket.shutdownOutput(); // 自动结束输出,否则两遍会陷入僵持状态,
        // 接受反馈
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);

        bw.close();
        socket.close();

    }
}

public class Receiver {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8008);
        Socket accept = serverSocket.accept();// 新建一个用于接收的socket对象,并获取输入流中的内容
        InputStream inputStream = accept.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test/java.java"));
        String line;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        // 给客户端反馈
        OutputStream outputStream = accept.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("RECEIVED!");
        bufferedWriter.newLine();
        bufferedWriter.flush();

        bw.close();
        serverSocket.close();
    }
}

练习6:多个不同的客户端向同一个服务端发送数据,服务端则要用多线程的方式来处理不同客户端的请求,为每一个请求建立一个线程,并且保证每次创建的文件名都不相同。

public class Receiver {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8008);

        while (true){
            Socket s = serverSocket.accept();// 新建一个用于接收的socket对象,并获取输入流中的内容
            new Thread(new ServerThread(s)).start();
        }

    }
}

public class ServerThread implements Runnable {
    private Socket s;
    public ServerThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            int count=0;
            File file = new File("idea_test/java"+count+".java");
            while (file.exists()){//直到创建了一个不重名的文件
                count++;
                file = new File("idea_test/java"+count+".java");
            }
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
                bw.flush();
            }

            // 给客户端反馈
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bufferedWriter.write("文件上传成功!");
            bufferedWriter.newLine();
            bufferedWriter.flush();

            s.close();

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

    }
}

在这里插入图片描述

public class BasicPractice {
public class BasicPractice {
    public static void main(String[] args) throws IOException {
        useFlyable((String s) -> System.out.println(s));
        System.out.println(useAddable((int x, int y) -> (x+y)));
    }

    public static void useFlyable(Flyable f){
        f.fly("fly");
    }

    public static int useAddable(Addable a){
        int sum = a.add(3, 5);
        return sum;
    }
}

方法引用


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

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        System.out.println(useConverter(Integer::parseInt));
        PrintString ps = new PrintString();
        usePrinter(ps::printUpper);
        useMyString(String::substring);
        useStudentBuilder(Student::new);
    }



    public static int useConverter(Converter c){
        int res = c.convert("123");
        return res;
    }

    public static void usePrinter(Printer p){
        p.printUpperCase("Hello");
    }

    public static void useMyString(MyString my){
        my.mySubString("hello", 1,3);
    }

    public static void useStudentBuilder(StudentBuilder s){
        s.build("nm", 20);
    }

}

在这里插入图片描述

import java.util.function.Supplier;

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        int[] a = {10,2,348,38,2};
        int m = getMax(()->{
            int max = a[0];
            for (int i=1;i<a.length;i++){
                if (a[i] > max){
                    max = a[i];
                }
            }
            return max;
        });
        System.out.println("max:" + m);
    }

    public static int getMax(Supplier<Integer> sup){
        Integer integer = sup.get();
        return integer;
    }

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        String[] str = {"林青霞,30", "张曼玉,35", "王祖贤,33"};
        for (int i=0;i<str.length;i++){
            useConsumer((String s) ->
            {   String[] split = s.split(",");
                System.out.print("姓名:" + split[0]); },
                    (String s) -> {System.out.println(",年龄:" + s.split(",")[1]);}, str[i]);
        }
    }

    public static void useConsumer(Consumer<String> c, Consumer<String> c2, String str){
//        c.accept(str[0]);
//        c2.accept(str[1]);
        Consumer<String> sc = c.andThen(c2);
        sc.accept(str);
    }

在这里插入图片描述

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        String[] str = {"林青霞,30", "张曼玉,35", "王祖贤,33"};
        ArrayList<String> al = new ArrayList<>();
        for (int i=0;i<str.length;i++){
            boolean b = usePredicate((String s) -> {
                String name = s.split(",")[0];
                return name.length() > 2;

            }, (String s) -> {
                Integer age = Integer.parseInt(s.split(",")[1]);
                return age > 33;
            }, str[i]);
            if (b){
                al.add(str[i]);
            }
        }
        for (String s:al){
            System.out.println(s);
        }
    }

    public static boolean usePredicate(Predicate<String> p1, Predicate<String> p2, String s){
//        boolean res = p1.test(s);
//        boolean res2 = p2.test(s);
        Predicate<String> and = p1.and(p2);
//        return res && res2;
        return and.test(s);
    }

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

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        String str = "林青霞,30";
        int i = useFunction(s -> Integer.parseInt(s.split(",")[1]) + 70, str);
        System.out.println(i);

    }

    public static int useFunction(Function<String, Integer> f, String s){
        Integer apply = f.apply(s);
        return apply;
    }

Stream流

public class BasicPractice {
    public static void main(String[] args) throws IOException {
        ArrayList<String> mal = new ArrayList<>();
        mal.add("周润发");
        mal.add("成龙");
        mal.add("刘德华");
        mal.add("吴京");

        ArrayList<String> wal = new ArrayList<>();
        wal.add("林心如");
        wal.add("张曼玉");
        wal.add("林青霞");
        wal.add("柳岩");

        Stream<String> ms = mal.stream().filter((String s) -> s.length() > 3);
        Stream<String> ws = wal.stream().filter((String s) -> s.startsWith("林")).skip(1);
        // map的参数是Function接口的lambda表达式,从一种类型转变为另一种类型,构造方法实现了从字符串类型转化为Actor类型
        Stream.concat(ms, ws).map(Actor::new).forEach((Actor a) -> System.out.println(a.getName()));


    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值