Java瞎学
常识
// JVM(Java Virtual Machine) java虚拟机
// JRE(Java Runtime Environment) java程序的运行时环境,包含 JVM 和 运行时所需要的核心类库
// JDK(Java Development Kit) java程序开发包,包含JRE和开发人员使用的工具
想要运行一个已有的java程序,只需安装JRE即可
要想开发一个全新的java程序,必须安装JDK
编写java源程序
编译java源文件 javac HelloWorld.java ==> HelloWorld.class
运行java程序 java HelloWorld
常量
变量
基本数据类型:整数、浮点数、字符、布尔
引用数据类型:类、数组、接口
// 方法的参数为基本类型时,传递的是数据值
// 方法的参数为引用类型时,传递的是地址值
// Java虚拟机的内存划分
堆内存:存储对象或者数组,new来创建的,都存储在堆内存
方法栈:方法运行时使用的内存,比如main方法运行,进入方法栈中执行
方法区:存储可以运行的class文件
Java数据类型
基本数据类型:整数 浮点数 字符 布尔
引用数据类型:类 数组 接口
四类八种基本数据类型:
字节型
短整型
整型
长整型
单精度浮点数
双精度浮点数
字符型
布尔类型
数据类型转换
范围小的类型 向 范围大的类型提升,byte short char 运算时直接提升为int
byte short char --> int --> long --> float --> double
强制类型转换:将取值范围大的类型 强制转换成 取值范围小的类型
自动转换是Java自动执行的,而强制转换需要手动执行
装箱和拆箱
装箱:从基本类型 转换为 对应的包装类对象
拆箱:从包装类对象 转换为 对应的基本类型
除了Character类之外,其他所有包装类都具有parseXxx静态方法,可以将字符串参数转换为对应的基本类型
public static int parseInt(String s)
int num = Integer.parseInt("100");
数组
// 定义数组
int[] arr = new int[3];
int[] arr = new int[] {1, 2, 3};
int[] arr = {1, 2, 3};
统计字符数组中每个字符出现的次数
public class Test {
public static void main (String[] args) {
// 获取长度100的字符数组
char[] charArray = {'a','l','f','m','f','o','b','b','s','n'};
// 统计字符数组中字母出现次数
printCount(charArray);
}
public static void printCount(char[] charArray) {
int[] count = new int[26];
// 对应保存字母出现的次数
for (int i = 0; i < charArray.length; i++) {
int c = charArray[i];
count[c - 97]++;
}
// 打印字母,次数
for (int i = 0, ch = 97; i < count.length; i++, ch++) {
if (count[i] != 0) {
System.out.println((char) ch + "--" + count[i]);
}
}
}
}
统计高于平均分的分数有几个
public class Solution {
public static void mian (String[] args) {
// 获取随机分数
int[] score = {95, 92, 75, 56, 98, 71, 80, 58, 91, 91};
// 获取平均分
int avg = getAvg(score);
// 定义计数的变量
int count = 0;
for (int i = 0; i < score.length; i++) {
if (score[i] > avg) {
count++;
}
}
System.out.println("高于平均分:" + avg + "的个数有" + count + "个");
}
// 获取平均分的方法
public static int getAvg(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
}
判断数组中的元素值是否对称
public class Solution {
public static boolean sym (int[] arr) {
for (int start = 0, end = arr.length - 1; start <= end; start++, end--) {
if (arr[start] != arr[end]) {
return false;
}
}
return true;
}
public static void main (String[] args) {
int[] arr = {};
System.out.println(Arrays.toString(arr) + "是否对称" + sym(arr));
}
}
比较数组内容是否完全一致
public class Solution {
public static boolean equals (int[] arr1, int[] arr2) {
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
}
符合JavaBean规范的类
public class Studnet {
// 成员变量
private String name;
private int age;
// 构造方法
public Student() {}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// 成员方法
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
// 测试类
public class TestStudent {
public static void main(String[] args) {
Student s = new Student();
s.setName("")
}
}
Scanner类 引用类型的使用步骤
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Random的使用步骤
import java.util.Random;
Random r = new Random();
int number = r.nextInt(10);
ArrayList类
ArrayList<String> list = new ArrayList<String>();
public boolean add(E e)
public E remove(int index)
public E get(int index)
public int size()
Arrays类
java.util.Arrays 此类中包含用来操作数组的各种方法,所有方法均为静态方法
public static String toString(int[] a) 返回指定数组内容的字符串表示形式
public static void sort(int[] a)
多态的好处
在实际开发中,父类类型作为方法的形式参数,传递子类对象给方法,进行方法的调用
引用类型转换
多态的转型分为:向上转型 和 向下转型
向上转型:多态本身是子类类型向父类类型向上转换的过程,这个过程是默认的
父类类型 变量名 = new 子类类型()
Animal a = new Cat()
向下转型:父类类型向子类类型向下转换的过程,这个过程是需要强制的
想要调用子类特有的方法,必须做向下转型
子类类型 变量名 = (子类类型) 父类变量名
Cat c = (Cat) a;
final关键字
final: 不可改变,用于修饰类、方法、变量
类:被修饰的类,不能被继承
方法:被修饰的方法,不能被重写
变量:被修饰的变量,不能被重新赋值
java.util.Collection 单列集合
Collection 接口(List接口 Set接口
数组的长度是固定的,集合的长度是可变的
集合存储的都是对象,而且对象的类型可以不一致
Collection 常用功能
public boolean add(E e) 把给定的对象添加到当前集合中
public void clear() 清空集合中所有的元素
public boolean remove(E e) 把给定的对象在当前集合中删除
public boolean contains(E e) 判断当前集合中是否包含给定的对象
public boolean isEmpty() 判断当前集合是否为空
public int size() 返回集合中元素的个数
public Object[] toArray() 把集合中的元素,存储到数组中
List接口中常用的方法(ArrayList LinkedList实现类
public void add(int index, E element)
public E get(int index)
pulic E remove(int index)
public E set(int index, E element)
泛型
集合中可以存放任意对象,把集合存储到集合后,都会被提升为Object对象。
当我们取出每一个对象,并且进行相应的操作时,必须采取类型转换
泛型:可以在类或方法中预支地使用未知的类型
// 当集合明确类型后,存放类型不一致就会编译报错
// 集合已经明确具体存放的元素类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素类型
// 当使用Iterator<String>控制元素类型后,就不需要强转了。获取到的元素直接就是String类型
排序方法 按照第一个单词的降序
public class CollectionDemo {
public static void main (String[] args) {
ArrayList<String> list = new ArrayList<String>();
// 排序方法 按照第一个单词的降序
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.charAt(0) - o1.charAt(0);
}
});
System.out.println(list);
}
}
创建一个学生类,存储到ArrayList集合中完成指定排序操作
// Student 初始类
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.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 String toString() {
return "Student{" + "name="........
}
@Override
public int compareTo(Student o) {
return this.age - o.age; // 升序
}
}
使用独立的定义规则
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// 年龄排序
int result = o2.getAge() - o1.getAge(); // 年龄降序
if (result == 0) {
result = o1.getName().charAt(0) - o2.getName().charAt(0);
}
return result; // 姓名首字母 升序
}
})
java.util.Map 双列集合
Map接口中的常用方法
public V put (K key, V value)
public V remove(Object key)
public V get(Object key) map.get(key)
public Set<K> keySet() 获取Map集合中所有的键,存储到Set集合中
public Set<Entry<K, V>> entrySet() 获取到Map集合中所有的键值对对象的集合(Set集合)
Entry将键值对的对应关系封装成了对象——键值对对象
从每一个键值对Entry对象中获取对应的键和对应的值
public K getKey()
public V getValue()
Map集合遍历键值对方式,HashMap保证成对元素唯一,并且查询速度很快
public class MapDemo {
public static void main(String[] args) {
// 创建Map集合对象
HashMap<String, String> map = new HashMap<String, String>();
// 获取 多有的entry对象 entrySet
Set<Entry<String, String>> entrySet = map.entrySet();
// 遍历得到每个entry对象
for (Entry<String, String> entry : entrySet) {
// 解析
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "的cp是" + value);
}
}
}
如果要保证有序,可以使用LinkedHashMap
public class LinkedHashMapDemo {
public static void main(String[] args) {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
Map 计算一个字符串中每个字符出现次数
public class MapTest {
private static void findChar(String line) {
// 创建一个集合 存储 字符 及其 出现的次数
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
// 遍历字符串
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
Integer count = map.get(c);
map.put(c, ++count);
}
}
System.out.println(map);
}
}
递归打印多级目录
public class DiGuiDemo02 {
public static void main(String[] args) {
// 创建File对象
File dir = new File("D:\\aaa");
// 调用打印目录方法
printDir(dir);
}
public static void printDir(Filr dir) {
// 获取子文件和目录
File[] files = dir.listFiles();
/*
循环打印
判断:
当是文件时,打印绝对路径
当是目录时,继续调用打印目录的方法,形成递归调用
*/
for (File file : files) {
if (file.isFile()) {
System.out.println("文件名" + file.getAbsolutePath());
} else {
System.out.println("目录" + file.getAbsolutePath());
printDir(file);
}
}
}
}
搜索D:\aaa目录中的.java文件
public class DiGuiDemo03 {
public static void main(String[] args) {
// 创建File对象
File dir = new File("D:\\aaa");
// 调用打印目录方法
printDir(dir);
}
public static void printDir(File dir) {
// 获取子文件和目录
File[] files = dir.listFiles();
for (File file : filrs) {
if (file.isFile()) {
if (file.getName().endsWith(".java")) {
System.out.println("文件名:" + file.getAbsolutePath());
}
} else {
printDir(file);
}
}
}
}
文件过滤器优化
// 使用匿名内部类
public class DiGuiDemo04 {
public static void main(String[] args) {
File dir = new File("D:\\aaa");
printDir2(dir);
}
public static void printDir2(File dir) {
File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".java") || pathname.isDirectory();
}
});
// 循环打印
for (File file : files) {
if (file.isFile()) {
System.out.println("文件名" + file.getAbsolutePath());
} else {
printDir2(file);
}
}
}
}
// 使用lambda (因为FileFilter是只有一个方法的接口)
public class DiGuiDemo04 {
public static void main(String[] args) {
File dir = new File("D:\\aaa");
printDir3(dir);
}
public static void printDir3(File dir) {
File[] files = dir.listFile(f -> {
return f.getName().endsWith(".java") || f.isDirectory();
});
}
}
匿名内部类
// 定义接口
public abstract class FlyAble {
public abstract void fly();
}
// 创建匿名内部类,并调用
public class InnerDemo {
public static void main(String[] args) {
FlyAble f = new FlyAble() {
@Override
public void fly() {
System.out.println("");
}
};
// 调用fly方法,执行重写后的方法
f.fly();
}
}
## 接口 定义格式
public interface 接口名称 {
// 抽象方法 使用abstract修饰,可以省略,没有方法体,该方法供子类实现使用
// 默认方法 使用default修饰,不可省略,供子类调用 或 子类重写(只能通过实现类的对象来调用)
// 静态方法 使用static修饰,供接口直接调用
// 私有方法 使用private修饰,供接口中的默认方法 或 静态方法调用
}
通常在方法的形参是借口或者抽象类时,可以将匿名内部类作为参数传递
// 定义接口
public abstract class FlyAble {
public abstract void fly();
}
public class InnerDemo2 {
public static void main(String[] args) {
FlyAble f = new FlyAble() {
@Override
public void fly() {
System.out.println();
}
};
// 将f传递给showFly方法中
showFly(f);
}
public static void showFly(FlyAble f) {
f.fly();
}
}
// 进一步简化
public class InnerDemo3 {
public static void showFly(FlyAble f) {
f.fly();
}
public static void main(String[] args) {
// 创建匿名内部类,直接传递给showFly(FlyAble f)
showFly(new FlyAble() {
@Override
public void fly() {
System.out.println();
}
});
}
}
定义HandleAble接口,具备一个处理字符串数字的抽象方法HandleString(String num),包括取整数部分 和 保留指定位小数
interface HandleAble {
public abstract String handleString(String str);
}
public class Test {
public static void main (String[] args) {
String str = "22.335343";
System.out.println("原来的数字字符串:" + str);
HandleAble s1 = new HandleAble() {
@Override
public String handleString(String str) {
return str.substring(0, str.indexOf("."));
}
};
String string = s1.handleString(str);
System.out.println("取整后:" + string);
int num = 4;
HandleAble s2 = new HandleAble() {
@Override
public String handleString(String str) {
int i = str.indexOf(".") + num + 1;
char c = str.charAt(i);
if (c <= '4') {
return str.substring(0, i).toString();
} else {
char c1 = (char) (str.charAt(str.indexOf(".") + num) + 1);
return str.substring(0, i - 1) + c1;
}
}
};
String sss = s2.handleString(str);
System.out.println("保留" + num + "位小数后:" + sss);
}
}
interface作为成员变量
// 定义接口
public interface FaShuKill {
public abstract void faShuAttack();
}
// 定义角色类
public class Role {
FaShuKill fs;
public void setFaShuKill(FaShuKill fs) {
this.fs = fs;
}
// 法术攻击
public void faShuKillAttack() {
System.out.println("");
fs.faShuAttack();
System.out.println();
}
}
// 定义测试类
public class Test {
public static void main (String[] args) {
// 创建游戏角色
Role role = new Role();
// 设置角色法术技能
role.setFaShuKill(new FaShuKill() {
@Override
public void faShuAttack() {
System.out.println("纵横天下");
}
});
// 发动法术攻击
role.faShuKillAttack();
// 更换技能
role.setFaShuKill(new FaShuKill() {
@Override
public void faShuAttack() {
System.out.println("逆转乾坤");
}
});
// 发动新的法术攻击
role.faShuKillAttack();
}
}
使用一个接口,作为成员变量,以便于随时更换技能,这样的设计更为灵活,增强了程序的扩展性
模拟群主给群成员发红包,群主自己打开最后一个红包(接口作为成员变量
RedPacketFrame:一个抽象类,包含了一些属性
public abstract class RedPacketFrame extends JFrame {
// 群主名称
public String ownerName = "谁谁谁";
// 红包的类型:普通红包/手气红包
public OpenMode openMode = null;
// 构造方法 生成红包界面
public RedPacketFrame(String title) {
super(title);
init(); // 页面相关的初始化操作
}
// set方法
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public void setOpenMode(OpenMode openMode) {
this.openMode = openMode;
}
}
OpenMode: 一个接口,包含一个分配方法,用来制定红包类型
public interface OpenMode {
public abstract ArrayList<Integer> divide (int totalMoney, int count);
}
/*
totalMoney:总金额
count:红包个数
ArrayList<Integer> 元素为各个红包的金额值,所有元素的值累计和为总金额
*/
定义RedPacket类,继承RedpacketFrame
public class RedPacket extends RedPacketFrame {
public RedPacket (String title) {
super(title);
}
}
定义测试类,创建Redpacket对象
public class RedPakcetTest {
public static void main (String[] args) {
// 创建红包对象
RedPacket rp = new RedPacket("大红包");
// 设置群主名称
rp.setOwnerName("我是群大大");
// 设置红包类型
rp.setOpenMode(new Common()); // 普通红包
rp.setOpenMode(new Lucky()); // 手气红包
}
}
普通红包,打开方式Common
public class Common implements OpenMode {
@Override
public ArrayList<Integer> divide (int totalMoney, int count) {
// 创建保存各个红包金额的集合
ArrayList<Integer> list = new ArrayList<>();
// 定义循环次数,总个数-1
int time = count - 1;
// 一次计算,生成平均金额
int money = totalMoney / count;
// 循环分配
for (int i = 0; i < time; i++) {
// 添加到集合中
list.add(money);
// 总金额扣除已分配金额
totalMoney -= money;
}
// 剩余的金额,为最后一个红包
list.add(totalMoney);
System.out.println("普通红包金额" + list);
return list;
}
}
手气红包,打开方式Lucky
public class Lucky implements OpenMode {
@Override
public ArrayList<Integer> divide (int totalMoney, int count) {
// 创建保存各个红包金额的集合
ArrayList<Integer> list = new ArrayList<>();
// 定义循环次数
int time = count - 1;
// 创建随机数对象
Random random = new Random();
// 循环分配
for (int i = 0; i < time; i++) {
int money = random.nextInt(totalMoney / count * 2) + 1;
list.add(money);
totalMoney -= money;
count--;
}
// 剩余的金额,为最后一个红包
list.add(totalMoney);
return list;
}
}
模拟人工挑苹果
class Worker {
public Apple pickApple(CompareAble c, Apple a1, Apple a2) {
Apple compare = c.compare(a1, a2);
return compare;
}
}
class Apple {
double size;
String color;
public Apple (double size, String color) {
this.size = size;
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
@Override
public String toString() {
return size + "-" + color;
}
}
interface CompareAble {
public default Apple compare(Apple a1, Apple a2) {
return a1.getSize() > a2.getSize() ? a1 : a2;
}
}
class Com implements CompareAble {
}
public class Test {
public static void main (String[] args) {
Worker worker = new Worker();
Apple apple1 = new Apple(5, "青色");
Apple apple2 = new Apple(3, "红色");
System.out.println("默认挑大的:");
Apple apple = worker.pickApple(new Com(), apple1, apple2);
System.out.println("挑红的:");
Apple apple3 = worker.pickApple(new Com(){
@Override
public Apple compare(Apple a1, Apple a2) {
return "红色".equals(a1.getColor()) ? a1 : a2;
}
}, apple1, apple2);
System.out.println(apple3)
}
}
模拟玩家选择角色(接口作为返回值
interface FightAble {
public abstract void specialFight();
public default void commonFight() {
System.out.println("普通打击");
}
}
class Player {
public FightAble select(String str) {
if ("法力角色".equals(str)) {
return new FaShi();
} else if ("武力角色".equals(str)) {
return new ZhanShi();
}
return null;
}
}
class FaShi implements FightAble {
@Override
public void sepcialFight() {
System.out.println("法术攻击");
}
}
class ZhanShi implements FightAble {
@Override
public void specialFight() {
System.out.println("武器攻击");
}
}
集合
在集合中,查找某元素,返回第一次出现的索引;将集合中的某元素,全部替换为新元素
public class Test {
public static int findIndex(List<Integer> list, int i) {
int index = -1;
for (int j = 0; j < list.size(); j++) {
if (list.get(j) == i) {
index = j;
break;
}
}
return index;
}
public static void replace (List<Integer> list, Integer oldValue, Integer newValue) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == oldValue) {
list.set(i, newValue);
}
}
}
}
键盘录入学生信息 保存到集合中
class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.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 void show() {
System.out.println("学生姓名=" + name + ", 年龄=" + age);
}
}
public class Test {
private static void inputStu (ArrayList<Student> list, Scanner sc) {
System.out.println("请输入姓名:");
String name = sc.next();
System.out.println("请输入年龄:");
int age = sc.nectInt();
Student student = new Student(name, age);
list.add(student);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Student> list = new ArrayList<>();
while (true) {
System.out.println("1.录入信息 0.退出");
int i = scanner.nextInt();
switch (i) {
case 1:
inputStu(list, scanner);
break;
case 0:
System.out.println("录入完毕")
}
if (i == 0) {
break;
}
}
for (int i = 0; i < list.size(); i++) {
Student student = list.get(i);
student.show();
}
}
}
删除list集合中所有长度 > 5 的字符串
public class Solution {
private static ArrayList<String> getArrayList() {
ArrayList<String> list = new ArrayList<>();
list.add("");
list.add("");
list.add("");
list.add("");
list.add("");
return list;
}
// 删除list集合中所有长度大于5的字符串
private static void delStrsFromList01 (ArrayList<String> list) {
// 创建ArrayList集合对象
ArrayList<String> newList = new ArrayList<String>();
// 遍历原集合对象
for (int i = 0; i < list.size(); i++) {
// 获取当前元素
String str = list.get(i);
if (str.length() > 5) {
newList.add(str);
}
}
// 遍历新集合
for (Object str : newList) {
list.remove(str);
}
}
}
Collection集合统计元素出现次数
public class Solution {
// 定义方法统计集合中指定元素出现的次数
public static int listTest (Collection<String> list, String s) {
// 定义计数器,初始化为0
int count = 0;
// 增强for遍历集合
for (String string : list) {
// 判断传入方法的字符与遍历集合的是否一致
if (s.equals(string)) {
count++;
}
}
return count;
}
}
Collection集合数组转集合
public class Solution {
public static ArrayList<Integer> listTest (int[] arr) {
// 定义集合
ArrayList<Integer> list = new ArrayList<Integer>();
// 遍历数组 把元素依次加到集合中
for (int a : arr) {
list.add(a);
}
return list;
}
}
String常用方法
public boolean equals (Object anObject) 将此字符串与指定对象进行比较
public int length() 返回字符串的长度
public String concat (String str) 将指定的字符串连接到该字符串的末尾
public char charAt (int index) 返回指定索引处的char值
public int indexOf (String str) 返回指定子字符串第一次出现在该字符串内的索引
public String substring (int beginIndex)
public String substring (int beginIndex, int endIndex)
public char[] toCharArray()
public byte[] getBytes()
public String replace()
public String[] split (String regex)
统计数字出现次数
public class Test {
public static ArrayList<Integer> getNumList() {
ArrayList<Integer> list = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < 100; i++) {
int x = r.randInt(10) + 1;
list.add(x);
}
return list;
}
public static void printCount (ArrayList<Integer> list) {
int[] count = new int[10];
// 对应保存数字出现的次数
for (int i = 0; i < list.size(); i++) {
int c = list.get(i);
count[c - 1]++;
}
// 打印数字和次数
for (int i = 0; i < count.lenth; i++) {
System.out.println("数字:" + (i + 1) + "--" + count[i] + "次");
}
}
}
反转键盘录入的字符串
public class Test {
public static String reverseStr (String str) {
String s = "";
char[] chars = str.toCharArray();
for (int i = chars.lenth - 1; i >= 0; i--) {
s += chars[i];
}
return s;
}
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String next = scanner.next();
System.out.println("录入的字符串:" + next);
String s = reverseStr(next);
System.out.println("反转的字符串:" + s);
}
}
键盘录入qq号,验证格式的正确性
public class Test {
public static boolean checkQQ (String qq) {
// 验证字符串的长度5-12位之间
if (qq.length() < 5 || qq.length() > 12) {
return false;
}
// 验证首位字符不能是字符0,只能是字符1-9
if (qq.charAt(0) == '0') {
return false;
}
// 验证字符串中的每个字符都必须是数字字符0-9之间的字符
for (int i = 0; i < qq.length(); i++) {
char ch = qq.charAt(i);
if (ch < '0' || ch > '9') {
return false;
}
}
return true;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String qq = sc.next();
boolean isOK = checkQQ(qq);
System.out.println("这个QQ号码是否正确:" + isOK);
}
}
键盘录入一个大字符串,再录入一个小字符串。统计小字符串在大字符串中出现的次数
public class Solution {
public static int getCount (String big, String small) {
int index = 0;
int count = 0;
while ((index = big.indexOf(small, index)) != -1) {
index++;
count++;
}
return count;
}
}
/*
* indexOf(String str, int fromIndex)
* 该方法作用:从fromIndex位置开始查找,字符
串str第一次出现的位置;若没找到,放回-1
*/
替换某字符串中的某字符串
public class Solution {
private static void printCount (String srcStr, String delStr) {
// 删除后的结果
String resultStr = srcStr.replace(delStr, "");
// 删除了几个delStr字符串
int count = (srcStr.length() - resultStr.length()) / delStr.length();
}
}
生成一个随机100内的小数,转换为保留两位小数的字符串,不考虑四舍五入问题
public class Solution {
public static void main (String[] args) {
double random = Math.random() * 100;
System.out.println("随机数为:");
System.out.println(random);
String str = random + "";
int index = str.indexOf(".");
String substring = str.substring(0, index + 3);
System.out.println("转换为:");
System.out.println(substring);
}
}
判断回文字符串
public class Solution {
public static boolean isP (String str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
if (str.charAt(start) != str.charAt(end)) {
return false;
}
start++;
end++;
}
return true;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String next = sc.next();
boolean p = isP(next);
System.out.println("回文数:" + p);
}
}
校验密码是否合法
public class Solution {
public static boolean isV (String pwd) {
if (pwd.length() < 8) {
return false;
}
int countA = 0;
char[] chars = pwd.toCharArray();
for (int i = 0; i < chars.length; i++) {
char ch = chars[i];
// 2个 大写字符
if (ch >= 'A' && ch <= 'Z') {
countA++;
}
// 字母数字
if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'Z') && (ch < 'a' || ch > 'z')) {
return false;
}
}
if (countA < 2) {
return false;
}
return true;
}
}
模拟用户登陆
public class Solution {
static ArrayList<User> list = new ArrayList<>();
static {
list.add(new User("jack", "1234"));
list.add(new User("rose", "4444"));
list.add(new User("tom", "0000"));
for (int i = 0; i < list.size(); i++) {
list.get(i).show();
}
}
public static String login (User user) {
String msg = "";
String n = user.getUsername();
String p = user.getPwd();
for (int i = 0; i < list.size(); i++) {
User u = list.get(i);
String name = u.getUsername();
String pwd = u.getPwd();
if (name.equals(n)) {
if (pwd.equals(p)) {
return "登陆成功";
} else {
return "密码错误";
}
} else {
msg = "用户名不存在";
continue;
}
}
return msg;
}
}
class User {
private String username;
private String pwd;
public User() {
}
public User (String username, String pwd) {
this.username = username;
this.pwd = pwd;
}
public String getUsername() {
return username;
}
public void setUsername (String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public void show() {
System.out.println(username + "-" + pwd);
}
}
文件读写操作
复制图片文件 FileInputStream|FileOutputStream 字节流
public class Copy {
public static void main (String[] args) throws IOException {
// 1.创建流对象
// 1.1 指定数据源
FileInputStream fis = new FileInputStream("D:\\test.jpg");
// 1.2 指定目的地
FileOutputStream fos = new FileOutputStream("test_copy.jpg");
// 2.读写数据
// 2.1 定义数组
// 2.2 定义长度
// 2.3 循环读取
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
fos.write(b, 0, len);
}
// 3.关闭资源
fos.close();
fos.close();
}
}
字节缓冲流 FileInputStream|FileOutputStream ==> BufferedInputStream|BufferedOutputStream
// 1 基本流
public class BufferedDemo {
public static void main(String[] args) throws FileNotFoundException {
// 记录开始时间
long start = System.currentTimeMills();
// 创建流对象
try (
FileInputStream fis = new FileInputStream("jdk9.exe");
FileOutputStream fos = new FileOutputStream("copy.exe")
) {
// 读写数据
int b;
while ((b = fis.read()) != -1) {
fos.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
// 记录结束时间
long end = System.currentTimeMills();
System.out.println("普通流复制时间:" + (end - start) + "毫秒");
}
}
// 2 缓冲流
public class BufferedDemo {
public static void main (String[] args) throws FileNotFoundException {
// 记录开始时间
long start = System.currentTimeMills();
// 创建流对象
try (
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
) {
// 读写数据
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
} catch(IOException e) {
e.printStackTrace();
}
// 记录结束时间
long end = System.currentTimeMills();
System.out.println("缓冲流复制时间" + (end - start) + "毫秒");
}
}
// 使用数组的方式
public class BufferedDemo {
public static void main (String[] args) throws FileNouFoundException {
// 记录开始时间
long start = System.currentTimeMills();
// 创建流对象
try (
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
) {
// 读写数据
int len;
byte[] bytes = new byte[8 * 1024];
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
// 记录结束时间
long end = System.currentTimeMillis();
System.out.println("缓冲流使用数组复制时间:" + (end - start) + "毫秒");
}
}
文本排序 FileReader|FileWriter 字符流 ==> BufferedReader|BufferedWriter字符缓冲流
public class BufferedTest {
public static void main(String[] args) throws IOException {
// 创建map集合,保存文本数据,key为序号,value为文字
HashMap<String, String> lineMap = new HashMap<>();
// 创建流对象
BufferedReader br = new BufferedReader(new FileReader("in.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
// 读取数据
String line = null;
while ((line = br.readLine()) != null) {
// 解析文本
String[] split = line.split("\\.");
// 保存到集合
lineMap.put(split[0], split[1]);
}
br.close();
// 遍历map集合
for (int i = 1; i <= lineMap.size(); i++) {
String key = String.valueOf(i);
// 获取map中文本
String value = lineMap.get(key);
// 写出拼接文本
bw.write(key + "." + value);
// 写出换行
bw.newLine();
}
// 释放资源
bw.close();
}
}
指定编码读取 InputStreamReader
public class ReaderDemo2 {
public static void main (String[] args) throws IOException {
// 定义文件路径,文件为gbk编码
String FileName = "E:\\file_gbk.txt";
// 创建流对象,默认为UTF8编码
InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName));
InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName), "GBK");
// 定义变量 保存字符
int read;
// 使用默认编码字符流读取,乱码
while((read = isr.read()) != -1) {
System.out.println((char)read); // 显示乱码
}
isr.close();
// 使用正确的编码字符流读取
while((read = is2.read()) != -1) {
System.out.println((char)read);
}
isr2.close();
}
}
指定编码写出 OutPutStreamWriter
public class OutPutDemo {
public static void main(String[] args) throws IOException {
// 定义文件路径
String FileName = "E:\\out.txt";
// 创建流对象,默认为utf8编码
OutPutStreamWriter osw = new OutPutStreamWriter(new FileOutputStream(FileName));
// 写出数据
osw.write("你好");
osw.close();
// 定义文件路径
String FileName2 = "E:\\out2.txt";
// 创建流对象,指定GBK编码
OutPutStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2), "GBK");
// 写出数据
osw2.write("你好");
osw2.close();
}
}
转化文件编码(将GBK编码的文本文件,转为utf8编码的文本文件)
public class TransDemo {
public static void main (String[] args) {
// 定义文件路径
String srcFile = "file_gbk.txt";
String destFile = "file_utf8.txt";
// 创建流对象
// 转换输入流 指定GBK编码
InputStreamReader isr = new InputStreamReader(new FileInput)
}
}
字节输出流写出字节数据
public class Solution {
public static void main (String[] args) {
// 创建字节输出流FileOutputStream对象并指定文件路径
FileOutputStream fos = new FileOutputStream("d:/a.txt");
// 调用字节输出流的write(int byte)方法写出数据
fos.write(97);
// 关闭流
fos.close();
}
}
字节输出流写出字节数组数据
public class Solution {
public static void main (String[] args) {
// 创建字节输出流FileOutputStream对象并指定文件路径
FileOutputStram fos = new FileOutputStream("d:/a.txt");
// 调用字节输出流write(byte[] buf) 方法写出数据
byte[] buf = "i love java".getBytes();
fos.write(buf);
// 关闭资源
fos.close();
}
}
文件的续写和换行输出
public class Solution {
public static void main (String[] args) {
// 创建字节输出流FileOutputSteam对象并指定文件路径,并追加方式
FileOutputStream fos = new FileOutputStream("c:/c.txt");
// 调用字节输出流的write方法写出数据
// 要输出的字符串
String content = "i love java \r\n";
for (int i = 0; i < 5; i++) {
fos.write(content.getBytes());
}
fos.close();
}
}
字节输入流一次读取一个字节数据
// 利用字节输入流读取D盘文件a.txt的内容,文件内容确定都为纯ASCII字符
public class Solution {
public static void main (String[] args) throws IOException {
// 创建字节输入流对象并关联文件
FileInputStream fis = new FileInputStream("d:/a.txt");
// 定义变量接收读取的字节
int len = -1;
// 循环从流中读取数据
while ((len = fis.read()) != -1) {
System.out.println((char)len);
}
fis.close();
}
}
字节输入流一次读取一个字节数组数据
public class Solution {
public static void main (String[] args) throws IOException {
// 创建字符输入流对象并关联文件
FileInputStream fis = new FileInputStream("d:/b.txt");
// 定义字节数组存放读取的字节数
byte[] buffer = new byte[1024];
// 定义变量接收读取的字节
int len = -1;
// 循环从流中读取数据
while ((len = fis.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len));
}
fis.close();
}
}
字节流复制文件
// 利用字节流将E盘下的a.png图片复制到D盘下
public class Solution {
public static void main (String[] args) throws IOExcepiotn {
// 创建字节输入流对象并关联文件
FileInputStream fis = new FileInputStream("e:/a.png");
// 创建字节输出流对象并关联文件
FileOutputStream fos = new FileOutputStream("d:/a.png");
// 定义变量接收读取的字节数
int len = -1;
// 循环读取图片数据
while ((len = fis.read()) != -1) {
// 每读取一个字节的数据就写出到目标文件中
fos.write(len);
}
fis.close();
fos.close();
}
}
字符输出流写出字符数据
// 用户从控制台输入信息,程序将信息存储到文件info.txt中
public class Solution {
public static void main (String[] args) throws IOException {
// 指定输出流,对应文件Info.txt
FileWriter bw = new FileWriter("Info.txt");
// 采用循环的方式,把每条信息存储一行到Info.txt中
Scanner sc = new Scanner(System.in);
while (true) {
// 获取键盘输入的一行内容
System.out.println("请输入内容:");
String str = sc.nextLine();
if ("886".equals(str)) {
break;
}
// 把内容写入到Info.txt文件中
bw.write(str);
// 换行
bw.write(System.lineSeparator());
}
bw.close();
}
}
IO对象Properties结合使用,设置properties文件
public class Solution {
public static void main (string[] args) throws IOException {
// 创建一个空的集合
Properties prop = new Properties();
// 读取数据到集合中
prop.load(new FileInputStream("score.txt"));
// 遍历集合,获取到每一个key
Set<String> keys = prop.stringPropertyNames();
// 获取到每一个key
for (String key : keys) {
if ("lisi".equals(key)) {
prop.setProperty(key, "100");
}
}
// 把集合中的所有信息,重新存储到文件中
prop.store(new FileOutputStream("score.txt"), "haha");
}
}
#### 高效字节输出流写出字节数据
```java
// 利用高效字节输出流往C盘下的d.txt文件输出一个字节数
public class Solution {
public static void main (String[] args) throws IOException {
// 创建字节输出流FileOutputStream对象并指定文件路径
FileOutputStream fos = new FileOutputStream("c:\\d.txt");
// 利用字节输出流创建高效字节输出流对象
BufferedOutputStream bos = new BufferedOutputStream(fos);
// 调用高效字节输出流对象的write(int byte)方法写出一个字节数据
bos.write(97);
// 关闭流
bos.close();
}
}
高效字节输出流写出字节数组数据
public class Solution {
public static void main (String[] args) throws IOException {
// 创建字节输出流FileOutputStream对象并指定文件路径
FileOutputStream fos = new FileOutputStream("c:\\e.txt");
// 利用字节输出流创建高效字节输出流对象
BufferedOutputStream bos = new BufferedOutputStream(fos);
// 调用高效字节输出流对象的write(bute[] buff) 方法写出一个字节数据
bos.write("i love java".getBytes());
}
}
高效流文件复制
public class Solution {
public static void main (String[] args) throws IOException {
// 创建字节输入流对象并关联文件路径
FileInputStream fis = new FileInputStream("c:\\c.png");
// 利用字节输出流对象创建高效字节输出流对象
BufferedInputStream bis = new BufferedInputStream(fis);
// 创建字节输出流对象并指定文件路径
FileOutputStream fos = new FileOutputStream("d:\\c.png");
// 利用字节输出流创建高效字节输出流对象
BufferedOutputStream bos = new BufferedOutputStream(fos);
// 定义字节数组接收读取的字节
byte[] buffer = new byte[1024];
// 定义变量接收读取的字节数
int len = -1;
// 循环读取图片数据
while ((len = bis.read(buffer)) != -1) {
// 每读取一个字节的数据就写出到目标文件中
bos.write(buffer, 0, len);
}
bis.close();
bos.close();
}
}
高效字符流 和 集合的综合使用
/*
实现一个验证码小程序,要求如下:
1. 在项目根目录下新建一个文件:data.txt,键盘录入3 个字符串验证码,并存入
data.txt 中,要求一个验证码占一行;
2. 键盘录入一个需要被校验的验证码,如果输入的验证码在data.txt 中存在:在控
制台提示验证成功,如果不存在控制台提示验证失败
*/
public class Solution {
public static void main (String[] args) throws IOException {
// 键盘录入3个字符串并写入项目根路径下的data.txt文件中
writeString2File();
// 验证码验证
verifyCode();
}
public static void verifyCode() throws Exception {
// 创建ArrayList集合,用于存储文件中的3个验证码
ArrayList<String> list = new ArrayList<>();
// 创建高效字符缓冲输入流对象,并和data.txt文件关联
BufferedReader br = new BufferedReader(new FileReader(new File("data.txt")));
String line = null;
// 循环读取每一行
while (null != (line = br.readLine())) {
// 将读到的每一行信息存入到list集合中
list.add(line);
}
// 关闭流对象
br.close();
// 创建键盘录入对象
Scanner sc = new Scanner(System.in);
// 提示用户输入验证码
System.out.println("请输入一个验证码");
String code = sc.nectLine();
if (list.contains(code)) {
System.out.println("验证成功");
} else {
System.out.println("验证失败");
}
}
// 键盘录入3个字符串并写入项目根路径下的data.txt文件中
private static void writeString2File() throws Exception {
// 创建高效字符缓冲流对象 并和 data.txt文件关联
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("data.txt")));
String line = null;
// 创建键盘录入对象
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("请输入第" + (i + 1) + "个字符串验证码");
// 读取用户键盘录入的一行验证码信息
line = sc.nextLine();
// 将读取到的一行验证码写入到文件中
bw.write(line);
// 写入换行符
bw.newLine();
}
// 关闭流对象
bw.close();
}
}
转换输出流的使用
public class Solution {
public static void main (string[] args) throws IOException {
// 要保存的字符串
String content = "我爱java";
// 创建字节输出流对象
FileOutputStream fos = new FileOutputStream("a.txt");
// 创建转换输出流对象
OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
// 调用方法写出数据
osw.write(content);
osw.close();
}
}
转换输入流的使用
public class Solution {
public static void main (String[] args) throws IOException {
// 创建字节输入流对象并关联文件
FileInputStream fis = new FileInputStream("a.txt");
// 创建转换输入流对象
InputStreamReader isr = new InputStreamReader(fis, "gbk");
// 定义字符数组存放读取的内容
char[] buffer = new char[1024];
// 定义变量接收读取的字符个数
int len = -1;
while ((len = isr.read()) != -1) {
System.out.println(new String(buffer, 0, len));
}
isr.close();
}
}
多线程
创建线程类方式一
public class Demo {
public static void main (String[] args) {
// 创建自定义线程对象
MyThread mt = new MyThread("新的线程");
// 开启新线程
mt.start();
// 在主方法中执行for循环
for (int i = 0; i < 10; i++) {
System.out.println("main线程" + i);
}
}
}
// 自定义线程类
public class MyThread extends Thread {
// 定义指定线程名称的构造方法
public MyThread(String name) {
// 调用父类的String参数的构造方法,指定线程的名称
super(name);
}
// 重写run方法,完成该线程执行的逻辑
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(getName() + ":正在执行" + i);
}
}
}
创建线程方式二
// 定义Runnable接口的实现类,并重写该接口的run()方法
// 创建Runnable实现类的实例,并以此实例作为Thread的target来创建Thread对象
// 调用线程对象的start()方法来启动线程
public class MyRunnable implements Runnable {
@Override
public void run () {
for (int i = 0; i < 20; i++) {
System.out.println(Thrad.currentThread().getName() + " " + i);
}
}
}
public class Demo {
public static void main (String[] args) {
// 创建自定义类对象 线程任务对象
MyRunnable mr = new MyRunnable();
// 创建线程对象
Thread t = new Thread(mr, "小强");
t.start();
for ()........
}
}
使用匿名内部类方式实现线程的创建
public class NoNameInnerClassThread {
public static void main (String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println();
}
}
};
new Thread(r).start();
for (int i =).....
}
}
public static void main (String[] args) {
new Thread (new Runnable() {
@Override
public void run () {
...
}
}, "线程名称").start();
}
线程同步:同步代码块 同步方法 锁
生产者与消费者问题
// 包子资源类
public class Baozi {
String pier;
String xianer;
boolean flag = false; // 包子资源 是否存在,包子资源状态
}
// 消费者进程类
public class ChiHuo extends Thread {
private BaoZi bz;
public ChiHuo (String name, BaoZi bz) {
super(name);
this.bz = bz;
}
@Override
public void run () {
while (true) {
synchronized (bz) {
if (bz.flag == false) {
try {
bz.wait();
} catch (InteruptedException e) {
e.printStackTrace();
}
}
System.out.println("正在吃" + bz.pier + bz.xianer + "包子");
bz.flag = false;
bz.notify();
}
}
}
}
// 生产者线程类
public class BaoZiPu extends Thread {
private BaoZi bz;
public BaoZiPu (String name, BaoZi bz) {
super(name);
this.bz = bz;
}
@Override
public void run () {
int count = 0;
while (true) {
synchronized (bz) {
if (bz.flag == true) {
try {
bz.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("包子铺开始做包子");
if (count % 2 == 0) {
bz.pier = "冰皮";
bz.xianer = "伍仁";
} else {
bz.pier = "baopi";
bz.xianer = "niuroudacong";
}
count++;
bz.flag = true;
System.out.println()
}
}
}
}
线程池使用步骤
// 创建线程池对象
// 创建Runnable接口子类对象(task
// 提交Runnable接口子类对象(take task
// 关闭线程池(一般不做
// Runnable实现类
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("我要一个教练");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("教练来了" + Thread.currentThread().getName());
System.out.println("教练教完")
}
}
// 线程池测试类
public class ThreadPoolDemo {
// 创建线程池对象 包含两个线程对象
ExecutorService service = Executors.newFixedThreadPool(2);
// 创建Runnable实例对象
MyRunnable r = new MyRunnable();
// 自己创建线程对象的方式
Thread t = new Thread(r);
t.start();
// 从线程池获取线程对象,然后调用MyRunnable中的run()
service.submit(r);
}
lambda表达式
创建对象 && 使用匿名内部类
// 为Runnable接口定义一个实现类
public class RunnableImpl implements Runnable {
@override
public void run() {
System.out.println("多线程任务执行");
}
}
// 创建该实现类的对象
public class Demo03ThreadInitParam {
public static void main(String[] args) {
Runnable task = new RunnableImpl();
new Thread(task).start();
}
}
// ============================================================
// 使用匿名内部类
public class Demo4ThreadNameless {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("多线程任务执行");
}
}).start();
}
}
1 使用Lambda必须具有接口,且要求接口中有且仅有一个抽象方法
2 方法的参数或局部变量类型必须为Lambda对应的接口类型
使用lambda标准格式(无参无返回
public interface Cook {
void makeFood();
}
public class Demo05InvokeCook {
public static void main(String[] args) {
invokeCook(() -> {
System.out.println("吃饭啦");
});
}
public static void invokeCook(Cook cook) {
cook.makeFood();
}
}
传统写法对Person[]数组进行排序
import java.util.Arrays;
import java.util.Compartor;
public class Demo06Comparator {
public static void main(String[] args) {
// 本来年龄乱序的对象数组
Person[] array = {
};
// 匿名内部类
Comparator<Person> comp = new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
};
// comp为排序规则,即comparator接口实例
Arrays.sort(array, comp);
for (Person person : array) {
System.out.println(person);
}
}
}
lambda写法对Person[]数组进行排序
import java.util.Arrays;
public class Demo07ComparatorLambda {
public static void main(String[] args) {
Person[] array = {
};
Arrays.sort(array, (Person a, Person b) -> {
return a.getAge() - b.getAge();
});
for (Person person : array) {
System.out.println(person);
}
}
}
Lambda标准格式(有参有返回
// 定义接口 内含抽象方法calc可以将两个int数字相加得到和值
public interface Calculator {
int calc (int a, int b);
}
// 使用lambda的标准格式调用invokeCalc方法
public class Demo08InvokeCalc {
public static void main(String[] args) {
invokeCalc(120, 130, (int a, int b) -> {
return a + b;
});
}
public static void InvokeCalc (int a, int b, Calculator calculator) {
int result = calculator.calc(a, b);
System.out.println("结果是:" + result);
}
}
函数式接口
// 函数式接口:有且仅有一个抽象方法的接口
@FunctionalInterface
public interface MyFunctionalInterface {
void myMethod();
}
// 自定义函数式接口
// 定义好的MyFunctionalInterface函数式接口,作为方法的参数
public class Demo {
private static void doSomething(MyFunctionalInterface inter) {
inter.myMethod(); // 调用自定义的函数式接口方法
}
public static void main (String[] args) {
// 调用使用函数式接口的方法
doSomething(() -> System.out.println("lambda执行"));
}
}
Supplier接口(用来获取一个泛型参数指定类型的对象数据
import java.util.function.Supplier;
public class Demo08Supplier {
private static String getString(Supplier<String> function) {
return function.get();
}
public static void main(String[] args) {
String msgA = "Hello";
String msgB = "world";
System.out.println(getString(()->msgA + msgB));
}
}
求数组元素的最大值
// 求数组元素的最大值
public class Demo02Test {
public static void getMax(Supplier<Integer> sup) {
return sup.get();
}
public static void main(String[] args) {
int arr[] = {2, 3, 4};
int maxNum = getMax(()->{
int max = arr[0];
for (int i : arr) {
if (i > max) {
max = i;
}
}
return max;
});
System.out.println(maxNum);
}
}
Consumer接口
import java.util.function.Consumer;
public class Demo09Consumer {
private static void consumeString (Consumer<String> function) {
function.accept("hello");
}
public static void main(String[] args) {
consumeString(s -> System.out.println(s));
}
}
import java.util.function.Consumer;
public class DemoComsumerAndThen {
private static void consumeString(Consumer<String> one, Consumer<String> two) {
one.andThen(two).accept("Hello");
}
public static void main (String[] args) {
consumeString(
s -> System.out.println(s.toUpperCase()),
s -> System.out.println(s.toLowerCawse())
);
}
}
consume函数式接口 格式化打印信息
import java.util.function.Consumer;
public class DemoConsumer {
private static void printInfo (Consume<String> one, Consume<String> two, String[] array) {
for (String info : arr) {
one.andThen(two).accept(info);
}
}
public static void main (String[] args) {
String[] array = {};
printInfo(
s -> System.out.println(),
s -> System.out.println(),
array
);
}
}
Predicate接口
import java.util.function.Predicate;
public class Demo15PredicateTest {
private static void method(Predicate<String> predicate) {
boolean veryLong = predicate.test("HelloWorld");
System.out.println("字符串很长吗:" + veryLong);
}
public static void main(String[] args) {
method(s -> s.length() > 5);
}
}
### Pedicate接口使用
import java.util.function.Predicate;
public class Test {
public static void main (String[] args) {
Integer[] arr = {......};
// 使用lambda表达式创建Predicate对象p1,判断整数是否为自然数
Predicate<Integer> p1 = (s) -> s >= 0;
// 使用lambda表达式创建Predicate对象p2,判断整数的绝对值是否大于100
Predicate<Integer> p2 = (s) -> Math.abs(s) > 0;
// 使用lambda表达式创建Predicate对象p3,p3能判断整数是否为偶数
Predicate<Integer> p2 = (s) -> s % 2 == 0;
// 遍历arr,仅利用已创建的Predicate对象
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
for (Integer i : arr) {
// 统计自然数个数
if (p1.test(i)) {
count1++;
}
// 统计负整数个数
if (p1.negate().test(i)) {
count2++;
}
// 统计绝对值大于100的偶数的个数
if (p2.and(p3).test(i)) {
count3++;
}
// 统计是负整数或者偶数的数的个数
if (p1.negate().or(p3).test(i)) {
count4++;
}
}
// 分别打印结果
System.out.println(......);
.......
}
}
判断一个字符串既要包含大写H 又要包含大写W
import java.util.function.Predicate;
public class Demo16PredicateAnd {
private static void method (Predicate<String> one, Predicate<String> two) {
boolean isValid = one.and(two).test("HelloWorld");
System.out.println("字符串符合要求吗" + isValid);
}
public static void main (String[] args) {
method(
s -> s.contains("H"),
s -> s.contain("W")
);
}
}
集合信息筛选
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class DemoPredicate {
public static void main (String[] args) {
String[] array = {};
List<String> list = filter(array,
s -> "女".equals(s.split(",")[1]),
s -> s.split(",")[0].length() == 4
);
System.out.println(list);
}
private static List<String> filter(String[] array, Predicate<String> one, Predicate<String> two) {
List<String> list = new ArrayList<>();
for (String info : array) {
if (one.and(two).test(info)) {
list.add(info);
}
}
return list;
}
}
Function接口
// 将String类型转换为Integer类型
import java.util.function.Function;
public class Demo11FunctionApply {
private static void method (Function<String, Integer> function) {
int num = function.apply("10");
System.out.println(num + 20);
}
public static void main(String[] args) {
method(s -> Integer.parseInt(s));
}
}
### Function接口使用
import java.util.*;
import java.util.function.Function;
public class Test {
public static void main (String[] args) {
// 使用lambda表达式说分别将以下功能封装到Function对象中
// 求Integer类型ArrayList中所有元素的平均值
Function<ArrayList<Integer>, Integer> f1 = (list) -> {
Integer sum = 0;
for (Integer i : list) {
sum += i;
}
return sum / list.size();
};
// 将Map<String, Integer>中value存到ArrayList<Integer> 中
Function<Map<String, Integer>, ArrayList<Integer>> f2 = (map) -> {
Collection<Integer> values = map.values();
ArrayList<Integer> list = new ArrayList<>();
list.addAll(values);
return list;
};
// 将学生姓名和成绩封装到map中
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("", 60);
....
// 利用Function求平均成绩
Integer avg = f2.andThen(f1).apply(map);
System.out.println("学生平均成绩为:" + avg);
}
}
```java import java.util.function.Function;
public class Demo12FunctionAndThen {
private static void method (Function<String, Integer> one, Function<Integer, Integer> two) {
int num = one.andThen(two).apply("10");
System.out.println(num + 20);
}
public static void main (String[] args) {
method(str -> Integer.parseInt(str) + 10,
i -> i *= 10
);
}
}
<br>
<br>
<br>
```java
import java.util.function.Function;
public class DemoFunction {
private static int getAgeNum (String str,
Function<String, String> one,
Function<String, Integer> two,
Function<Integer, Ingeter> three) {
return one.andThen(two).andThen(three).apply(str);
}
public static void main (String[] args) {
String str = "ggl,10";
int age = getAgeNum (str,
s -> s.split(",")[1],
s -> Integer.parseInt(s),
n -> n += 100);
System.out.println(age);
}
}
函数式接口 定义一个函数式接口CurrentTimePrinter,其中抽象方法void printCurrentTime(),使用注解@FunctionalInterface
// TimePrinter接口
@FunctionalInterface
public interface CurrentTimePrinter {
void printCurrentTime();
}
// 测试类
public class Test {
public static void main (String[] args) {
showLongTime(() -> System.out.println(System.currentTimeMillis()));
}
public static void showLongTime (CurrentTimePrinter timePrinter) {
timePrinter.printCurrentTime();
}
}
定义一个函数式接口IntCalc,其中抽象方法int calc(int a , int b),使用注解@FunctionalInterface
// IntCalc接口
@FunctionalInterface
public interface IntCalc() {
int calc(int a, int b);
}
// 测试类
public class Test {
public static void main (String[] args) {
getProduct(2, 3, (a, b) -> a * b);
}
public static void getProduct (int a, int b, IntCalc intCalc) {
int product = intCalc.calc(a, b);
System.out.println(product);
}
}
静态方法引用 定义一个函数式接口NumberToString, 其中抽象方法String convert(int num) , 使用注解@FunctionalInterface
// NumberToString接口
@FunctionalInterface
public interface NumberToSting {
String convert (int num);
}
// 测试类
public class Test {
public static void decToHex (int num, NumberToString nts) {
String convert = nts.convert(num);
System.out.println(convert);
}
public static void main (String[] args) {
decToHex (999, Integer::toHexString);
}
}
如何获取流
// java.util.Collection 接口中加入了default方法 stream() 获取流对象,因此其所有实现类均可通过此方式获取流
// java.util.Map接口想要获取流,先通过keySet() values() 或 entrySet() 方法获取键、值或键值对,再通过stream()获取流对象
// 数组获取流,使用Stream接口中的静态方法of (T...values) 获取流
public static void main (String[] args) {
// 1.1
List<String> list = new ArrayList<>();
Stream<String> stream1 = list.stream();
// 1.2
Set<String> set = new HashSet<>();
Stream<String> stream2 = set.stream();
// 2
Map<String, String> map = new HashMap<>();
Stream<String> keyStream = map.keySet().stream();
Stream<String> valueStream = map.values().stream();
Stream<Map.Entry<String, String>> entryStream = map.entrySet().stream();
// 3
String[] array = {...};
Stream<String> stream = Stream.of(array);
}
过滤:filter、结果收集(数组
import java.util.stream.Stream;
public class Test {
public static void main (String[] args) {
Stream<String> stream = Stream.of(".."...);
String[] guos = stream.filter(s -> s.stratsWith("郭")).toArray(String[]::new);
}
}
取用前几个:limit、跳过前几个:skip
import java.util.ArrayList;
public class Test {
public static void main (String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("...");
list.add("...");
list.add("...");
list.add("...");
list.add("...");
// 取出前2个元素并在控制台打印输出
list.stream().limit(2).forEach(System.out::println);
// 取出后2个元素并在控制台打印输出
list.stream().skip(list.size() - 2).forEach(System.out::println);
}
}
映射:map、逐一消费:forEach
import java.util.stream.Stream;
public class Test {
public static void main (String[] args) {
Stream<Integer> stream = Stream.of(1, -2, -3);
stream.map(Math::abs).forEach(System.out::println);
}
}
组合:concat、结果收集(list
import java.util.stream.Stream;
public class Test {
public static void main (String[] args) {
Stream<String> streamA = Stream.of("..", "....");
Stream<String> streamB = Stream.of("..", "....");
List<String> strList = Stream.concat(StreamA, StreamB).collect(Collectors.toList());
}
}
Stream流
import java.util.ArrayList;
import java.util.List;
public class Demo03StreamFilter {
public static void main (String[] args) {
List<String> list = new ArrayList<>();
list.add("");
list.add("");
list.add("");
list.stream()
.filter(s -> s.startsWith("zhang"))
.filter(s -> s.length() == 3)
.forEach(System.out::println);
}
}
逐一处理: forEach
import java.util.stream.Stream;
pubilc class Demo012StreamForEach {
public static void main(String[] args) {
Stream<String> stream = Stream.of("", "", "");
stream.forEach(name -> System.out.println(name));
}
}
过滤:filter
import java.util.stream.Stream;
public class Demo07StreamFilter {
public static void main(String[] args) {
Stream<String> original = Stream.of("", "", "");
Stream<String> result = original.filter(s -> s.startsWith("张"));
}
}
映射:map
import java.util.stream.Stream;
public class Demo08StreamMap {
public static void main(String[] args) {
Stream<String> original = Stream.of("", "", "");
Stream<Integer> result = original.map(str -> Integer.parseInt(str));
}
}
统计个数 count
import java.util.stream.Stream;
public class Demo09StreamCount {
public static void main(String[] args) {
Stream<String> original = Stream.of("", "", "");
Stream<String> result = original.filter(s -> s.startsWith("zhang"));
System.out.println(result.count());
}
}
方法引用
@FunctionalInterface
public interface PrintableInteger {
void print(int str);
}
public class Demo03PrintOverLoad {
private static void printInteger(PrintableInteger data) {
data.print(1024);
}
public static void main(String[] args) {
printInteger(System.out::println);
}
}
通过对象名引用成员方法
// 定义一个类 其中有一个成员方法
public class MethodRefObject {
public void printUpperCase(String str) {
System.out.println(str.toUpperCase());
}
}
// 函数式接口
@FunctionalInterface
public interface Printable {
void print(String str);
}
public class DemoMethodRef {
private static void printString(Printable lambda) {
lambda.print("cumt");
}
public static void main(String[] args) {
MethodRefObject obj = new MethodRefObject();
printString(obj::printUpperCase);
}
}
通过类名称引用静态方法
@FunctionalInterface
public interface Calcable {
int calc(int num);
}
// 使用lambda表达式
public class DemoLambda {
private static void method(int num, Calcable lambda) {
System.out.println(lambda.calc(num));
}
public static void main(String[] args) {
method(-10, n -> Math.abs(n));
}
}
// 使用方法引用
public class DemoMethodRef {
private static void method(int num, Calcable lambda) {
System.out.println(lambda.calc(num));
}
public static void main(String[] args) {
method(-10, Math::abs);
}
}
通过super引用成员方法
@FunctionalInterface
public interface Greetable {
void greet();
}
// 父类
public class Human {
public void sayHello() {
System.out.println("hello");
}
}
// zi lei 使用Lambda
public class Man extends Human {
@Override
public void sayHello() {
System.out.println("我是M an");
}
// 定义方法method 参数传递Greetaable接口
public void method(Greetable g) {
g.greet();
}
public void show() {
// 第一种写法
method(() -> {
// 创建Human对象
new Human().sayHello();
});
// 第二种写法 使用super关键字代替父类对象
method(() -> super.sayHello());
}
}
// zi lei 使用方法引用
public class Man extends Human {
@Override
public void sayHello() {
System.out.println("woshiMan");
}
// 定义方法method 参数传递Greetable接口
public void method(Greetable g) {
g.greet();
}
public void show() {
method(super::sayHello);
}
}
通过this引用成员方法
@FunctionalInterface
public interface Richable {
void buy();
}
public class Husband {
private void buyHouse() {
System.out.println("mai tao fang zi");
}
private vois marry(Richable lambda) {
lambda.buy();
}
public void baHappy() {
marry(this::buyHouse);
}
}
类的构造器引用
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// 创建Person对象的函数式接口
public interface PersonBuilder {
Person buildPerson(String name);
}
// 通过Lambda表达式使用这个函数式接口
public class Demo09Lambda {
public static void printName(String name, PersonBuilder builder) {
System.out.println(builder.buildPerson(name).getName());
}
public static void main(String[] args) {
printName('gengguanglei', name -> new Person(name))
}
}
// 通过构造器引用,使用这个函数式接口
public class Demo10ConstructorRef {
public static void printName(String name, PersonBuilder builder) {
System.out.println(builder.builderPerson(name).getName());
}
public static void main(String[] args) {
printName("gengguanglei", Person::new);
}
}
数组的构造器引用
@FunctionalInterface
public interface ArrayBuilder {
int[] buildArray(int length);
}
// 使用lambda表达式使用该接口
public class Demo11ArrayInitRef {
private static int[] initArray(int length, ArrayBuilder builder) {
return builder.buildArray(length);
}
public static void main(String[] args) {
int[] array = initArray(10, length -> new int[length]);
}
}
// 使用数组的构造器引用使用该函数式接口
public class Demo123ArrayInitRef {
private static int[] initArray(int length, ArrayBuilder builder) {
return builder.buildArray(length);
}
public static void main(String[] args) {
int[] array = initArray(10, int[]::new);
}
}
用户登陆
# 用户登陆案例需求:
1 编写login.html登陆页面,username & password 两个输入框
2 使用Druid数据库连接池技术,操作mysql,day14数据库中user表
3 使用JdbcTemplate技术封装JDBC
4 登陆成功跳转到SuccessServlet展示:登陆成功 用户名,欢迎您
5 登陆失败跳转到FailServlet展示:登陆失败,用户名或密码错误
开发步骤
1 创建项目,导入html页面,配置文件,jar包
2 创建数据库环境
create database day14;
use day14;
create table user(
id int primary key auto_increment,
username varchar(32) unique not null,
password varcher(32) not null
);
3 创建包cn.itcast.domain,创建类User
package cn.itcast.domain;
// 用户的实体类
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
4 创建包cn.itcast.util,编写工具类JDBCUtils
package cn.itcast.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
// JDBC工具类
public class JDBCUtils {
private static DataSource ds;
static {
try {
// 1 加载配置文件
Properties pro = new Properties();
// 使用ClassLoader加载配置文件,获取字节输入流
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
// 2 初始化连接池对象
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
// 获取连接池对象
public static DataSource getDataSource() {
return ds;
}
// 获取连接Connection对象
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
// 5 创建包cn.itcast.dao, 创建类UserDao, 提供login方法
package cn.itcast.dao;
import cn.itcast.domain.User;
import cn.itcast.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
// 操作数据库中User表的类
public class UserDao {
// 声明JDBCTemplate对象共用
private jdbcTemplate template = new jdbcTemplate(JDBCUtils.getDataSource());
// 登陆方法
public User login(User loginUser) {
try {
// 编写sql
String sql = 'select * from user where username = ? and password = ?';
// 调用query方法
User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPassword());
return user;
} catch (DataAccessException e) {
e.printStackTrace();
return null;
}
}
}
// 6 编写cn.itcast.web.servlet.LoginServlet类
package cn.itcast.web.servlet;
import cn.itcast.dao.UserDao;
import itcast.domain.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1 设置编码
rep.setCharacterEncoding("utf-8");
// 2 获取请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
// 3 封装user对象
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);
// 4 调用UserDao的login方法
UserDao dao = new UserDao();
User user = dao.login(loginUser);
// 4 调用UserDao的login方法
UserDao dao = new UserDao();
User user = dao.login(loginUser);
// 5 判断user
if (user == null) {
// 登陆失败
req.getRequestDispatch("/failServlet").forward(req, resp);
} else {
// 登陆成功
// 存储数据
req.setAttribute("user", user);
// 转发
req.getRequestDispatch("/successServlet").forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
// 7 编写FailServlet 和 SuccessServlet 类
@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取request域中共享的user对象
User user = (User) request.getAttribute("user");
if (user != null) {
// 给页面写一句话
// 设置编码
response.setContentType("text/html;charset=utf-8");
// 输出
response.getWriter().write("登陆成功" + user.getUsername() + "欢迎");
}
}
}

浙公网安备 33010602011771号