ArrayList初步使用

✏️Practice the usage of ArrayList all of String with a exampe of NoteBook.

📒ArrayList all of String的部分函数用法练习,以记事本的例子进行实现 , 顺便练习了一下成员函数的创建及使用。
做了一个记事本的程序,可以实现添加、删除、获取指定内容、改变指定内容(增删改查)、获取记事本的内容数量、指定位置插入的功能。
✂️学习把代码的业务逻辑部分和人机交互部分分离的思想。
🔘暂时还存在较多的代码重复的地方,还需要优化代码,暂时实现了基本的功能。
代码如下

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

public class NoteBook {
    ArrayList<String> notes = new ArrayList<>();

    public void add(String s) {
        notes.add(s);
    }

    public String in() {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        return s;
    }

    public String remove(int index) {
        return (notes.remove(index));
    }

    public int getSize() {
        int i = notes.size();
        return i;
    }

    public String getNote(int index) {
        return new String(notes.get(index));
    }

    public void insert(int index, String s) {
        notes.add(index, s);
    }

    public String change(int index, String s) {
        return (notes.set(index, s));
    }

    public static void main(String[] args) {
        NoteBook nb = new NoteBook();

        // 输入记录的内容储储存到notes中
        System.out.println("输入记录内容");
        String s = "";
        while (!s.equals("结束")) {
            s = nb.in();
            nb.add(s);
        }
        nb.remove(nb.getSize()-1);
        System.out.println("内容已记录");

        // 获取notes的总条数
        int total;
        total = nb.getSize();
        System.out.println("一共有" + total + "条");

        // 删除内容
        System.out.println("请输入要删除第几条记录");
        int index;
        Scanner in = new Scanner(System.in);
        index = in.nextInt() - 1;
        s = nb.remove(index);
        System.out.println("已删除记录:" + s);

        // 获取指定位置的内容
        System.out.println("请输入要查询第几条");
        index = in.nextInt()-1;
        s=nb.getNote(index);
        System.out.println("内容是:"+s);

        // 指定位置插入指定内容
        System.out.println("请输入要插入的位置");
        index = in.nextInt();
        System.out.println("请输入要插入的内容");
        s=in.nextLine();
        nb.insert(index,s);
        System.out.println("插入成功");

        // 替换指定位置的内容
        System.out.println("请输入要替换的位置");
        index = in.nextInt();
        System.out.println("请输入要替换扥内容");
        s= in.nextLine();
        nb.change(index,s);
        System.out.println("替换成功");
    }
}
posted @ 2020-06-12 15:18  juyss  阅读(163)  评论(0)    收藏  举报