【题目描述】
用Java语言实现记事本小程序:
1、能够储存数据
2、不限制储存数据的数量
3、能查看存储的每一条记录
4、用户可以删除指定的数据
5、能够输出所有的数据记录
【学习目标】
在实现此程序的同时,更重要的是掌握利用容器类实现对数据的存储(对数组的改良),以及掌握容器类的一系列常用操作。
【解题步骤及详解】
1、引入容器类及创建对象:
import java.util.ArrayList;
private ArrayList<String> notes = new ArrayList<String>();
注释:在引用泛型类的时候,要指明两个类型,一个是类的类型,一个是容器类中所存储元素的类型。
2、在Notebook类中创建各个接口:
add(String note);
getSize();
getNote(int index);
removeNote(int index);
list();
3、利用类容器的各种工具来将各个接口中的功能实现:
a.add接口:
public void add(String s)
{
notes.add(s);
}
注释:利用类容器给我们提供的add工具函数实现对字符串的储存,代替字符串数组来实现此功能。字符串数组需我们手动设定其存储长度,而本程序要求不限制存储数量,所以使用类容器更加合理,也是由此引出了类容器的概念。
b.getSize接口:
public void add(String s,int location)
{
notes.add(location,s);
}
注释:此代码块所实现的功能是将一个新进元素(字符串变量s)插入在下标为location变量的位置上 。在此步骤之后,原本此位置上的元素向后顺移一位。整个类容器中下标数量加一。
c. getNode接口:
public String getNote(int index)
{
return notes.get(index);
}
注释:此代码块通过下标索引的方式将用户输入容器类中指定位置上的元素进行输出。类比于数组的索引方式。
d.removeNode接口:
public void removeNote(int index)
{
notes.remove(index);
}
注释:与上述代码块原理相同,即通过下标索引的方式来删除指定位置上的元素。
e.List接口:
public String[] list()
{
String[]a=new String[notes.size()];
注释:此代码块通过创建一个字符串数组,将类容器中的全部元素按照用户输入的顺序依次进行输出。
【整体代码】
package notebook;
import java.util.ArrayList;
public class Notebook {
private ArrayList<String> notes = new ArrayList<String>();
public void add(String s)
{
notes.add(s);
}
public void add(String s,int location)
{
notes.add(location,s);
}
public int getSize()
{
return notes.size();
}
public String getNote(int index)
{
return notes.get(index);
}
public void removeNote(int index)
{
notes.remove(index);
}
public String[] list()
{
String[]a=new String[notes.size()];
}
public static void main(String[] args) {
Notebook elem=new Notebook();
elem.add("再见");
elem.add("你好");
elem.add("谢谢",1);
System.out.println(elem.getSize());
System.out.println(elem.getNote(1));
elem.removeNote(1);
String[] a=elem.list();
for(String s:a)
{
System.out.println(s);
}
}
}
【输出样例】
3
谢谢
再见
你好
【总结】
本题主要是通过建立这个记事本这个小程序来充分熟悉ArrayList类的一些操作 。