package 順序表;public class SqList {?? ?public Object[] listElem;//線性表存儲(chǔ)空間?? ?private int lengths;//線性表的長(zhǎng)度?? ?//順序表構(gòu)造函數(shù),構(gòu)造有個(gè)長(zhǎng)度為maxSize的線性表?? ?public SqList(int maxSize){?? ??? ?lengths=0;?? ??? ?listElem = new Object[maxSize];?? ?}?? ?//置空操作?? ?public void clear(){?? ??? ?lengths=0;?? ?}?? ?//判斷長(zhǎng)度是否為0,0即是空表?? ?public boolean isEmpty(){?? ??? ??? ?if(lengths>0){?? ??? ??? ??? ?System.out.println("非空");?? ??? ??? ?}?? ??? ??? ?return lengths==0;?? ?}?? ?//取表長(zhǎng)度,返回lengths的長(zhǎng)度?? ?public int length(){?? ??? ?return lengths;?? ?}?? ?//取表元素?? ?public Object get(int i)throws Exception{?? ??? ?//如果不合法報(bào)異常?? ??? ?if(i>0 || i>lengths-1){?? ??? ??? ?throw new Exception("第"+i+"個(gè)元素不存在");?? ??? ?}?? ??? ?return listElem[i];?? ?}?? ?//插入操作?? ?public void insert(int i,Object x) throws Exception{?? ??? ?if(lengths==listElem.length){?? ??? ??? ?throw new Exception("順序表已滿");?? ??? ?}?? ??? ?if(i<0 || i>lengths){?? ??? ??? ?throw new Exception("插入位置不合法");?? ??? ?}?? ??? ?//從尾部往前掃?? ??? ?for(int j=lengths;j>i;j--){?? ??? ??? ?listElem[j]=listElem[j-1];?? ??? ??? ?listElem[i]=x;?? ??? ??? ?lengths++;?? ??? ?}?? ?}?? ??? ?//刪除操作?? ??? ?public void remove(int i)throws Exception{?? ??? ??? ?if(i<0 || i>lengths-1){?? ??? ??? ??? ?throw new Exception("刪除位置不合法");?? ??? ??? ?}?? ??? ??? ??? ??? ??? ??? ?//下標(biāo)移動(dòng)要出刪除的i處?? ??? ??? ??? ?for(int j=i;j<lengths-1;j++){?? ??? ??? ??? ??? ?listElem[j]=listElem[j++];?? ??? ??? ??? ??? ?lengths--;?? ??? ??? ??? ?}?? ??? ??? ??? ??? ?}?? ??? ??? ?//查找操作?? ??? ??? ?public int Indexof(Object x){?? ??? ??? ??? ?int j=0;?? ??? ??? ??? ?//遍歷查找?? ??? ??? ??? ?while(j<lengths && !listElem[j].equals(x)){?? ??? ??? ??? ??? ?j++;?? ??? ??? ??? ?}?? ??? ??? ??? ?if(j<lengths){?? ??? ??? ??? ??? ?return j;?? ??? ??? ??? ?}else{?? ??? ??? ??? ??? ?return -1;?? ??? ??? ??? ?}?? ??? ??? ?}?? ??? ??? ?//顯示操作?? ??? ??? ?public void display(){?? ??? ??? ??? ?//遍歷線性表?? ??? ??? ??? ?for(int i=0;i<lengths;i++){?? ??? ??? ??? ??? ?System.out.println(listElem[i]);?? ??? ??? ??? ?}?? ??? ??? ?}?? ?public static void main(String[] args) throws Exception {?? ??? ?SqList sq=new SqList(20);?? ??? ??? ??? ?sq.insert(1,1);?? ??? ?sq.insert(2,8);?? ??? ?sq.insert(3,9);?? ??? ?sq.insert(4,8);?? ??? ?sq.insert(5,10);?? ??? ?sq.display();?? ?}?? ?}我搞不懂了怎么插入異常,我明明符號(hào)條件,請(qǐng)各位給我看下
用java實(shí)現(xiàn)順序表報(bào)異常
慕先生4463397
2017-11-24 22:25:35