顺序表:现有一学生情况一览表,要求依次输入学生信息并依次显示,假设元素个数不超过100。
package seq; interface List { public void insert(int i,Object obj)throws Exception; public Object getData(int i)throws Exception; public int size(); } class SeqList implements List { final int defaultSize=10; int maxSize; public int size; Object [] listArray; private void initiate(int sz) { maxSize=sz; size=0; listArray=new Object[sz]; } public SeqList(){ initiate(defaultSize); } public SeqList(int size){ initiate(size); } public void insert(int i,Object obj)throws Exception { if(size==maxSize) { throw new Exception("顺序表已满无法插入!"); } if(i<0||i>size) throw new Exception("参数错误!"); for(int j=size;j>i;j--) listArray[j]=listArray[j-1]; listArray[i]=obj; size++; } public Object getData(int i)throws Exception { if(i<0||i>=size) { throw new Exception("参数错误!"); } return listArray[i]; } public int size() {return size;} } class Studentt{ private String number; private String name; private String sex; private int age; Studentt(String number,String name,String sex,int age){ this.number = number; this.name = name; this.sex = sex; this.age = age; } public String getNumber(){ return number; } public String getName(){ return name; } public String getSex(){ return sex; } public int getAge(){ return age; } } //把学生对象存入顺序表并输出 public class SeqListTest2 { public static void main(String[] args) { SeqList seqList = new SeqList(100); Studentt []student = new Studentt[3]; student[0] = new Studentt("20151236","李娜","男",20); student[1] = new Studentt("20151233","李思","女",21); student[2] = new Studentt("20150125","王璇","女",22); try{ for(int i=0;i<student.length;i++){ seqList.insert(i,student[i]); } for(int j=0;j<seqList.size;j++){ Studentt st = (Studentt)seqList.getData(j); System.out.println(st.getNumber()+" "+st.getName()+" " +st.getSex()+" "+st.getAge()); } }catch(Exception e){ System.out.println(e.getMessage()); } } }