7.Java常用API(String、ArrayList)

API(Application Programming Interface, 应用程序编程接口)
Java写好的技术(功能代码),可以直接调用

1.String

String类定义的变量可以用于存储字符串,同时String类提供了很多操作字符串的功能,可以直接使用

String类的特点:String其实常被称为不可变字符串类型,它的对象在创建后不能被更改
以""方式给出的字符串对象,在字符串常量池中存储

String变量每次的修改其实都是产生并指向了新的字符串对象

1.创建字符串对象的2中方式

方式一:直接使用""定义

String name = "张三"

方式二: 通过String类的构造器创建对象

构造器说明
piblic String()创建一个空白字符串对象,不含有任何内容
public String(String original)根据传入的字符串内容,来创建字符串对象
public String(char[] chs)根据字符数组的内容,来创建字符串对象
public String(byte[] chs)根据字节数组的内容,来创建字符串对象
public class StringDemo2 {
    public static void main(String[] args) {
        // 1.public String() 创建一个空白字符串对象,不含有任何内容
        String s1 = new String();
        System.out.println(s1);

        // 2.public String(String) : 根据传入的字符串内容,来创建字符串对象
        String s2 = new String("张三");

        // 3. publlic String(char[] c) : 根据字符数组的内容,来创建字符串对象
        char[] chars = {'a', 'b', 'c' , 'd'};
        String s3 = new String(chars);
        System.out.println(s3); // abcd

        // 4.public String(byte[] b): 根据字节数组的内容,来创建字符串对象
        byte[] bytes = {100,120,45,67};
        String s4 = new String(bytes);
        System.out.println(s4);  // dx-C

        System.out.println("----------");
        String s5 = "abc";
        String s6 = "abc";
        System.out.println(s5 == s6); // true

        String s7 = new String(chars);
        String s8 = new String(chars);
        System.out.println(s7 == s8); // false
    }
}

两种创建对象的区别
以""方式给出的字符串对象,在字符串常量池中存储,而且相同内容只会在其中存储一份
通过构造器new对象,每new一次都会产生一个新对象,放在堆内存中

代码分析

String s2 = new String("abc");  // 这一句代码实际上创建了两个对象
String s1 = "abc";     // 这句代码创建了0个对象
System.out.println(s1 == s2) // false
String s1 = "abc";
String s2 = "ab";
String s3 = s2 + "c";
System.out.println(s1 == s3); // false
String s1 = "abc";
String s2 = "a" + "b" + "c";
System.out.println(s1 == s2); // true

Java存在编译优化机制,程序在编译时:“a” + “b” + “c” 会直接转成 “abc”

2.String类常用api

字符串比较不适合用 ==
推荐使用String类提供的"equals"比较:只关心内容一样即可

方法名说明
public boolean equals(Object anObject)将此字符串与指定对象进行比较,只关心字符内容是否一致
public boolean equalsIgnoreCase(String anotherString)将此字符串与指定对象进行比较,忽略大小写比较字符串,只关心字符串内容是否一致
public static void main(String[] args) {
   String name = "zhangsan";
    String password = "123456";

    // 2.请您输入登录名称和密码
    Scanner sc = new Scanner(System.in);
    System.out.println("登录名称:");
    String uname = sc.next();
    System.out.println("登录密码:");
    String upassword = sc.next();

//        if(uname == name && upassword == password) {
//            System.out.println("登录成功");
//        } else {
//            System.out.println("用户名或密码错误");
//        }
    if(uname.equals(name) && upassword.equals(password)) {
        System.out.println("登录成功");
    } else {
        System.out.println("用户明或密码错误");
    }
}

String常用API

方法名说明
public int length()获取字符串的长度
public char charAt(int index)获取某个索引位置处的字符
public char[] toCharArray()把字符串转换成字符串数组
public String substring(int beginIndex, int endIndex)包前不包后(字符串截取)
public String substring(int beginIndex)从当前索引一致截取到末尾
public String replace(CharSequence target, CharSequence replacement)替换
public boolean containes(CharSequence s)判断字符串中是否包含
public boolean startWiths(String prefix)判断是否以某个字符串开始
public String[] split(String s)按照某个内容把字符串分割成字符串数组返回
public static void main(String[] args) {
        // 1.public int length() : 获取字符串的长度
        String name = "我是zhangsan";
        System.out.println(name.length());

        // 2.public char charAt(int index) 获取某个索引位置处的字符
        char c = name.charAt(2);
        System.out.println(c);
        System.out.println("遍历字符串中的每个数组");
        for (int i =0;i<name.length();i++) {
            char ch = name.charAt(i);
            System.out.println(ch);
        }

        // 3.public char[] toCharArray() : 把字符串转化成字符数组
        char[] chars = name.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char ch = chars[i];
            System.out.println(ch);
        }

        // 4.public String substring(int beginIndex. int endIndex): 截取内容,包前不包后
        String name2 = "mynameislisi";
        System.out.println(name2.substring(0, 3));

        // 5.public String substring(int beginIndex)
        System.out.println(name2.substring(2));

        // 6。public String replace(CharSequence target,CharSeqiece replacement)
        System.out.println(name2.replace("i", "爱"));

        // 7.public boolean containe(CharSequence s)
        System.out.println(name2.contains("i"));

        // 8.public boolean starsWith(String prefix)
        System.out.println(name2.startsWith("my"));

        // 9. public String[] split(String s):按照某个内容把字符串分割成字符串数组
        String name3 = "张三,李氏,张三丰,wuhu";
        String[] names = name3.split(",");
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }

    }

2.案例:String类开发验证码功能

public static void main(String[] args) {
    String datas = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890";

    Random r = new Random();
    String code = "";
    for (int i = 0; i < 5; i++) {
        // 随机一个索引
        int index = r.nextInt(datas.length());
        char c = datas.charAt(index);
        code += c;
    }

    System.out.println(code);
}

3.案例:模拟用户登录功能

模拟用户登录功能,最多只给三次机会

    public static void main(String[] args) {
        // 1.定义正确的登录名称和密码
        String okLoginName = "admin";
        String okPassword = "123456";

        // 2.定义一个循环,循环3次,让用户登录
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 3; i++) {
            System.out.println("请输入登录名称");
            String username = sc.next();
            System.out.println("请输入登录密码");
            String password = sc.next();

            // 3.判断登录名是否成功
            if(okLoginName.equals(username)) {
                if(okPassword.equals(password)) {
                    System.out.println("登录成功");
                    break;
                }else {
                    System.out.println("密码错误");
                }
            } else {
                System.out.println("用户名错误");
            }
        }
    }

4.案例:手机号屏蔽

以字符串的形式从键盘接收一个手机号,将中间四位数屏蔽

   public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请您输入您的手机号码");
        String tel = sc.next();

        // 截取号码的前三位,后四位
        String before = tel.substring(0,3);
        String after = tel.substring(7);
        String phone = before + "****" + after;

    }

5.ArrayList

集合与数组类似,也是一种容器,用于装数据的
数组的特点:数组定义完成并启动后,类型确定,长度固定
问题:在个数不能确定,且要进行增删数据操作的时候,数组是不太合适的

集合的特点:集合的大小不固定,启动后可以动态变化,类型也可以选择不固定
集合非常适合做元素个数不确定,且要进行增删操作的业务场景
集合提供了许多丰富好用的功能,而数组的功能很单一
ArrayList是集合中的一种,它支持索引

ArrayList集合的对象获取
public ArrayList() 创建一个空的集合对象

ArrayList集合添加元素的方法
public boolean add(E e) 将指定的元素追加到此集合的末尾
public void add(int index, E element) 在此集合中的指定位置插入指定的元素

public static void main(String[] args) {
    // 1.创建ArrayList集合的对象
    ArrayList list = new ArrayList();

    // 添加元素
    list.add("张三");
    list.add("李四");
    list.add("王五");
    System.out.println(list.add("赵六"));
    System.out.println(list);

    // 在指定索引插入元素
    list.add(1, "王二");
    System.out.println(list);
}

泛型
ArrayList:可以在编译阶段约束集合对象只能操作某种数据类型
ArrayList 此集合只能操作字符串类型的元素
ArrayList 此集合只能操作整数类型的元素
注意:集合中只能存储引用类型,不支持基本数据类型

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>(); // JDK 1.7开始,泛型后面的类型声明可以不写
    list.add("zhangsan");
    ArrayList<Integer> list2 = new ArrayList<Integer>();
    list2.add(22);
}

ArrayList集合常用方法

方法名称说明
public E get(int index)返回指定索引处的元素
public int size()返回集合中的元素的个数
public E remove(int index)删除指定索引处的元素,返回被删除的元素
public boolean remove(Object o)删除指定的元素,返回删除是否成功
public E set(int index, E element)修改指定索引处的元素,返回被修改的元素
public static void main(String[] args) {
    // 1.创建ArrayList集合的对象
    ArrayList<String> list = new ArrayList();
    list.add("张三");
    list.add("李四");
    list.add("王五");
    list.add("赵六");
    list.add("徐七");

    // 1.public E get(int index) 获取某个索引位置处的元素
    String e = list.get(2);
    System.out.println(e);

    // 2.public int size() 获取集合的大小(元素个数)
    System.out.println(list.size());

    // 3.完成元素遍历
    for (int i = 0; i < list.size(); i++) {
        String e1 = list.get(i);
        System.out.println(e1);
    }

    // 4.public E remove(int index)  删除某个索引位置的元素怒,并且返回被删除的元素
    System.out.println(list.remove(1));
    System.out.println(list);

    // 5.public boolean remove(Object o) 直接删除元素,删除成功返回true,失败返回false(若有多个相同元素,默认删除第一个)
    System.out.println(list.remove("张三"));
    System.out.println(list);

    // 6.public E set(int index, E element): 修改某个索引位置处的元素值,返回修改前的值
    System.out.println(list.set(0,"郭八"));
    System.out.println(list);
}

6.案例:遍历并删除元素值

需求:某个班级学生的分数集合,删除80分以下的值

public static void main(String[] args) {
    ArrayList<Integer> scores = new ArrayList();
    scores.add(89);
    scores.add(78);
    scores.add(94);
    scores.add(23);
    scores.add(87);
    scores.add(84);
    scores.add(97);
    scores.add(55);
    scores.add(66);
    scores.add(89);
    System.out.println(scores);

    // 1.遍历集合中的每个元素
    for (int i = scores.size()-1; i >= 0; i--) {
        int score = scores.get(i);
        if(score < 80) {
            scores.remove(i);
        }
    }
    System.out.println(scores);
}

7.案例:影片信息在程序中的表示

需求:某影院系统需要在后台存储三部电影,然后依次显示出来

public class Move {
    private String name;
    private double score;
    private String actor;

    public Move() {
    }

    public Move(String name, double score, String actor) {
        this.name = name;
        this.score = score;
        this.actor = actor;
    }

    public String getName() {
        return name;
    }

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

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public String getActor() {
        return actor;
    }

    public void setActor(String actor) {
        this.actor = actor;
    }
}
    public static void main(String[] args) {
        // 1.定义一个电影类:move
        // 2.定义一个ArrayList集合存储这些影片对象
        ArrayList<Move> movies = new ArrayList();
        // 3,创建影片对象,封装电影数据,把对象加入到集合中
        Move m1 = new Move("约会大作战1", 7.8,"橘公司");
        Move m2 = new Move("约会大作战2", 7.9,"橘公司");
        Move m3 = new Move("约会大作战3", 6.0,"橘公司");
        movies.add(m1);
        movies.add(m2);
        movies.add(m3);
        // 4.遍历集合中的影片对象并展示出来
        for (int i = 0; i < movies.size(); i++) {
            Move m = movies.get(i);
            System.out.println("片名:"+m.getName()+"评分:"+m.getScore()+"作者:"+m.getActor());
        }
    }

集合中存储的元素并不是对象本身,而是对象的地址

8.案例:学生信息系统的数据搜索

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

    public Student() {
    }

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

    public String getStudyId() {
        return studyId;
    }

    public void setStudyId(String studyId) {
        this.studyId = studyId;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
}

    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList();
        students.add(new Student("201701","张三", 20, "软件工程1班"));
        students.add(new Student("201702","李四", 23, "软件工程2班"));
        students.add(new Student("201703","王五", 19, "计算机科学与技术1班"));
        students.add(new Student("201704","赵六", 21, "物联网工程2班"));
        System.out.println("学号\t\t班级\t\t姓名\t\t年龄");
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            System.out.println(s.getStudyId()+"\t\t"+s.getClassName()+"\t\t"+s.getName()+"\t\t"+s.getAge());
        }
        // 搜索
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请输入要查找的学号");
            String id = sc.next();
            Student s = getStudentByStudyId(students, id);
            if(s == null) {
                System.out.println("查无此人");
            } else {
                System.out.println(s.getStudyId()+"\t\t"+s.getClassName()+"\t\t"+s.getName()+"\t\t"+s.getAge());
            }
        }
    }
    /*
    * @param students
    * @param studyId
    * */
    public  static Student getStudentByStudyId(ArrayList<Student> students, String studyId) {
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            if(s.getStudyId().equals(studyId)) {
                return  s;
            }
        }
        return null;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值