摆脱Java nullpointerexception和arrayindexoutofbound异常

问题描述

|| 我在随机事件上得到这些例外。有时它们会发生。有时它们不会 请运行此代码,并帮助我摆脱它们
package my.matcher;
//导入java.util.Calendar; 公共类Matcher {
/*public static class priceHeap{
    int price;
    int orderid;
    int quantity;

    priceHeap(){
        price = 0;
        orderid = 0;
        quantity = 0;
    }
}*/

//private int price;
//private int type;

public static class PriceNode{
    int price;

    int logid;
    public PriceNode(){

    }
}
PriceNode[] buyPriceHeap = new PriceNode[maxHeapSize];
PriceNode[] sellPriceHeap = new PriceNode[maxHeapSize];

public static int temp_logid = 0;

public static int orderNum=0;
public static int TradeNum=0;
public static int buyOrderNum=0;
public static int sellOrderNum=0;

public static int totalOrders=0;
public static int checkMatchReturn=2;
public static final int maxHeapSize = 40000;

//public static int[] sellPriceHeap = new int[maxHeapSize];
//public static int[] buyPriceHeap = new int[maxHeapSize];

public static int buyHeapSize = 0;
public static int sellHeapSize = 0;

   public static class Order{ 

    int orderid;
    int price;
    int quantity;
    int logid;
    Order(){
        orderid = 0;        
        price = 0;
        quantity = 0;
        logid = 0;
    }
}
public static final int maxOrders = 100;
public static int buyOrderArraySize = 0;
public static int sellOrderArraySize = 0;

Order[] buyOrderArray = new  Order[maxOrders];
Order[] sellOrderArray = new Order[maxOrders];

public void siftUpMax(int child){
    int parent,tmp1,tmp2;
    if(child != 0){
        parent = (child-1)/2;
        if(buyPriceHeap[parent].price < buyPriceHeap[child].price){
            tmp1 = buyPriceHeap[parent].price;
            tmp2 = buyPriceHeap[parent].logid;
            buyPriceHeap[parent].price = buyPriceHeap[child].price;
            buyPriceHeap[parent].logid = buyPriceHeap[child].logid;
            buyPriceHeap[child].price = tmp1;
            buyPriceHeap[child].logid = tmp2;
            siftUpMax(parent);
        }

    }
}


public void siftUpmin(int child){
    int parent,tmp2;
    if(child != 0){
        parent = (child-1)/2;
        if(sellPriceHeap[parent].price > sellPriceHeap[child].price){
            tmp1 = sellPriceHeap[parent].price;
            tmp2 = sellPriceHeap[parent].logid;
            sellPriceHeap[parent].price = sellPriceHeap[child].price;
            sellPriceHeap[parent].logid = sellPriceHeap[child].logid;
            sellPriceHeap[child].price = tmp1;
            sellPriceHeap[child].logid = tmp2;
            siftUpmin(parent);
        }

    }
}


public void buyPriceHeapInsert(int num,int id){
    if(buyHeapSize == buyPriceHeap.length){
        System.out.println(\"OVerflow\");
    }
    else{
        buyHeapSize++;
        buyPriceHeap[buyHeapSize-1] = new PriceNode();
        buyPriceHeap[buyHeapSize-1].price = num;
        buyPriceHeap[buyHeapSize-1].logid = id;
        siftUpMax(buyHeapSize-1);
    }
    return;
    }
public void sellPriceHeapInsert(int num,int id){
    if(sellHeapSize == sellPriceHeap.length){
        System.out.println(\"OverFlow\");
    }
    else{
        sellHeapSize++;
        sellPriceHeap[sellHeapSize-1] = new PriceNode();
        sellPriceHeap[sellHeapSize-1].price = num;
        sellPriceHeap[sellHeapSize-1].logid = id;
        siftUpmin(sellHeapSize-1);
    }
    return;
}

public void buyPriceHeapDelete(){
    //int temp = buyPriceHeap[0];
    buyPriceHeap[0].logid = buyPriceHeap[buyHeapSize-1].logid;
    buyPriceHeap[0].price = buyPriceHeap[buyHeapSize-1].price;
    buyHeapSize--;
    if(buyHeapSize > 0){
        siftDownMax(0);
    }
    }//Need to find a better way to delete from heap in java.

public void siftDownMax(int parent){
    int left,right,max,tmp2;
    left = (2*parent) + 1;
    right = (2*parent) + 2;
    if(right >= buyHeapSize){
        if(left >= buyHeapSize)
            return;
        else
            max = left;
    }
    else{
        if(sellPriceHeap[left].price >= sellPriceHeap[right].price)
            max = left ;
        else
            max = right;                            
    }
    if(sellPriceHeap[parent].price < sellPriceHeap[max].price){
        tmp1 = sellPriceHeap[parent].logid;
        tmp2 = sellPriceHeap[parent].price;
        sellPriceHeap[parent].logid = sellPriceHeap[max].logid;
        sellPriceHeap[parent].price = sellPriceHeap[max].price;
        sellPriceHeap[max].logid = tmp1;
        sellPriceHeap[max].price = tmp2;
        siftDownMin(max);
    }
}

public void sellPriceHeapDelete(){

    //int temp = sellPriceHeap[0];
    sellPriceHeap[0].logid = sellPriceHeap[sellHeapSize-1].logid;
    sellPriceHeap[0].price = sellPriceHeap[sellHeapSize-1].price;
    sellHeapSize--;
    if(sellHeapSize > 0){
        siftDownMin(0);
    }
}

public void siftDownMin(int parent){
    int left,min,tmp2;
    left = (2*parent) + 1;
    right = (2*parent) + 2;
    if(right >= sellHeapSize){
        if(left >= sellHeapSize)
            return;
        else
            min = left;
    }
    else{
        if(sellPriceHeap[left].price <= sellPriceHeap[right].price)
            min = left ;
        else
            min = right;                            
    }
    if(sellPriceHeap[parent].price > sellPriceHeap[min].price){
        tmp1 = sellPriceHeap[parent].logid;
        tmp2 = sellPriceHeap[parent].price;
        sellPriceHeap[parent].logid = sellPriceHeap[min].logid;
        sellPriceHeap[parent].price = sellPriceHeap[min].price;
        sellPriceHeap[min].logid = tmp1;
        sellPriceHeap[min].price = tmp2;
        siftDownMin(min);
    }
}

public int buyPriceHeapMax(){

    int maxBuy = 0;

    for(int i=0;i<buyHeapSize;i++){
        maxBuy = buyPriceHeap[0].price;
        if(buyPriceHeap[i].price>maxBuy){
            maxBuy = buyPriceHeap[i].price;
        }           
    }
    return maxBuy;
}

public int sellPriceHeapMin(){
    int minSell = 0;

    for(int i=0;i<sellHeapSize;i++){
        minSell = sellPriceHeap[0].price;
        if(sellPriceHeap[i].price<minSell){
            minSell = sellPriceHeap[i].price;
        }           
    }
    return minSell;
}



/*public void setPrice(int p){
    price = p;
}
public void setType(int t){
    type = t;
}
*/
/ * public void checkType(int t){         如果(t == 1){             System.out.println(\“购买订单\”);         }         其他{             System.out.println(\“销售订单\”);         }     } * /
public void checkMatch(int p,int t,int q,int id){


    if(t==1){//Buy
        buyOrderNum++;

        if(sellPriceHeap[0].price != 0 && sellPriceHeap[0].price < p){

            TradeNum++;
            int log_id = sellPriceHeap[0].logid;
             //System.out.println(\"The active Buy Order has been matched with a Sell Order\");
            //System.out.println(\"Buy Order Price : \" + p);
            //int x = sellPriceHeapMin();
            //System.out.println(\"Sell Order Price : \" + x);
            quantityCheck(p,q,t,id,log_id);
            //System.out.println(\"Both the entries have been Removed from the storage\");
            //System.out.println(\"Now We Move On to the next Entry\");
            checkMatchReturn=1;
            return;
        }
        else{
            checkMatchReturn=2;
            }


}

    else if(t==2){//Sell
        sellOrderNum++;
        if(buyPriceHeap[0].price!=0 && buyPriceHeap[0].price > p){

                    int log_id = buyPriceHeap[0].logid;
                    TradeNum++;
                    //System.out.println(\"The active Sell Order has been matched with a Buy Order\");
                    //System.out.println(\"Sell Order Price : \" + p);
                    //int y = buyPriceHeapMax();
                    //System.out.println(\"Buy Order Price : \" +y);
                    quantityCheck(p,log_id);
                    //System.out.println(\"Both the entries have been Removed from the storage\");
                    //System.out.println(\"Now We Move On to the next Entry\");
                    checkMatchReturn=1;
                    return;


        }
            else{
                checkMatchReturn=2;
            }
        }


    return;
}
public void buyOrderArrayInsert(int id,int p,int q){
    buyOrderArraySize++;
    int i = buyOrderArraySize-1;
    buyOrderArray[i] = new Order();
    buyOrderArray[i].orderid = id;
    buyOrderArray[i].price = p;
    buyOrderArray[i].quantity = q;
    temp_logid = i;
    //int index = Arrays.binarySearch(buyPriceHeap,i);

}

public void sellOrderArrayInsert(int id,int q){
    sellOrderArraySize++;
    int i = sellOrderArraySize-1;
    sellOrderArray[i] = new Order();
    sellOrderArray[i].orderid = id;
    sellOrderArray[i].price = p;
    sellOrderArray[i].quantity = q;
    temp_logid = i;
}

public void quantityCheck(int p,int qty,int id,int lid){
    int match = 0;
    if(t==1){

                match = lid;


        int qmatch = sellOrderArray[match].quantity;
        if(qmatch == qty){
            sellPriceHeapDelete();
            //System.out.println(\"Quantities of Both Matched Entries were same\");
            //System.out.println(\"Both Entries Removed\");
            return;
        }
        else if(qty < qmatch){
            int temp = qmatch - qty;
            sellOrderArray[match].quantity=temp;
            //System.out.println(\"The Active Buy Order Has been Removed\");
            //System.out.println(\"The Passive Sell Order Has Been Updated\");
            return;
        }
        else if(qty > qmatch){
            int temp = qty - qmatch;
            sellPriceHeapDelete();
            //System.out.println(\"The Passive Sell Order Has Been Removed\");
            buyOrderArrayInsert(id,p,temp);
            //System.out.println(\"The Active Buy Order Has Been Updated and Added\");
            buyPriceHeapInsert(p,temp_logid);
            removeSellOrder(match);
            return;
        }
    }
    else if(t==2){
        //Active is Sell Order

                match = lid;


        int qmatch = buyOrderArray[match].quantity;
        if(qmatch == qty){
            buyPriceHeapDelete();
            //System.out.println(\"Quantities of Both Matched Entries were same\");
            //System.out.println(\"Both Entries Removed\");
            return;
        }
        else if(qty < qmatch){
            int temp = qmatch - qty;
            buyOrderArray[match].quantity=temp;
            //System.out.println(\"The Active Sell Order Has been Removed\");
            //System.out.println(\"The Passive Buy Order Has Been Updated\");
            return;
        }
        else if(qty > qmatch){
            int temp = qty - qmatch;
            buyPriceHeapDelete();
            //System.out.println(\"The Passive Sell Order Has Been Removed\");
            sellOrderArrayInsert(id,temp);
            //System.out.println(\"The Active Buy Order Has Been Updated and Added\");
            sellPriceHeapInsert(p,temp_logid);
            removeBuyOrder(match);
            return;
        }
    }
}

public void removeSellOrder(int n){
    sellOrderArray[n].orderid=0;
    sellOrderArray[n].price=0;
    sellOrderArray[n].quantity=0;

    if(n < sellOrderArraySize - 1){
        for(int i=n+1;i<sellOrderArraySize;i++){
            int tempid = sellOrderArray[i-1].orderid;
            int tempprice = sellOrderArray[i-1].price;
            int tempqty = sellOrderArray[i-1].quantity;

            sellOrderArray[i-1].orderid=sellOrderArray[i].orderid;
            sellOrderArray[i-1].quantity=sellOrderArray[i].quantity;
            sellOrderArray[i-1].price=sellOrderArray[i].price;

            sellOrderArray[i].orderid = tempid;
            sellOrderArray[i].price = tempprice;
            sellOrderArray[i].quantity = tempqty;
        }
    }


}

public void removeBuyOrder(int n){
    buyOrderArray[n].orderid=0;
    buyOrderArray[n].price=0;
    buyOrderArray[n].quantity=0;

    if(n < buyOrderArraySize - 1){
        for(int i=n+1;i<buyOrderArraySize;i++){
            int tempid = buyOrderArray[i-1].orderid;
            int tempprice = buyOrderArray[i-1].price;
            int tempqty = buyOrderArray[i-1].quantity;

            buyOrderArray[i-1].orderid=buyOrderArray[i].orderid;
            buyOrderArray[i-1].quantity=buyOrderArray[i].quantity;
            buyOrderArray[i-1].price=buyOrderArray[i].price;

            buyOrderArray[i].orderid = tempid;
            buyOrderArray[i].price = tempprice;
            buyOrderArray[i].quantity = tempqty;
        }
    }
}
/*
void printBuyOrder(int[] a){
    System.out.println(\"The Buy Order List is : \");
    for(int i=0;i<buyOrderArraySize;i++){
        System.out.println(\" Order ID = \" + buyOrderArray[i].orderid);            
        System.out.println(\" Price = \" + buyOrderArray[i].price);
        System.out.println(\" Quantity = \" + buyOrderArray[i].quantity);
        System.out.println(\"---------------------\");
    }
}*/

public static void main(String[] args){
    int inprice=0,intype=0,inquantity=0,inorderid=0,x=0;
    long startTime=0,endTime=0;
    Matcher ob = new Matcher();
    ob.buyPriceHeap[x] = new PriceNode();
    ob.sellPriceHeap[x] = new PriceNode();
    //Calendar Now = Calendar.getInstance();
    //int s1 = Now.get(Calendar.SECOND);
    startTime = System.nanoTime();
    for (int i=0;i<maxOrders;i++){
        inprice = (int) (Math.random() *500 +1 );
        intype = (int) (Math.random() *2 +1);
        inquantity = (int) (Math.random() *100 +1);
        inorderid = i;
        orderNum++;

        //ob.setPrice(inprice);
        //ob.setType(intype);
        //System.out.println(\"orderid : \"+ inorderid + \" price : \" +inprice + \" type : \" + intype + \"quantity : \" + inquantity);
        ob.checkMatch(inprice,intype,inquantity,inorderid);
        if(checkMatchReturn == 2){
            //System.out.println(\"No Matching Order\");
            if(intype==1){


                    ob.buyOrderArrayInsert(inorderid,inprice,inquantity);
                    ob.buyPriceHeapInsert(inprice,temp_logid);

                //System.out.println(\"The Unmatched Order is then inserted Into the Buy Order List\");
                }
            if(intype==2){


                    ob.sellOrderArrayInsert(inorderid,inquantity);
                    ob.sellPriceHeapInsert(inprice,temp_logid);

                //System.out.println(\"The Unmatched Order is then inserted Into the Sell Order List\");
            }
                }
            }
    //int s2 = Now.get(Calendar.SECOND);
    /*System.out.println(\"The Pending Orders in the lists are : \");
    System.out.println(\" ~~~~~ Buy Order List ~~~~~ \");
    for(int x=0;x<buyHeapSize;x++){
        System.out.print(\" \"+ buyPriceHeap[x]);

        }
    System.out.println(\" ~~~~~ Sell Order List ~~~~~ \");

    for (int y=0;y<sellHeapSize;y++){ 
        System.out.print(\" \" + sellPriceHeap[y]);
        System.out.println(\"\");
        }*/
    //int tiMetaken = s2-s1;

    endTime = System.nanoTime();
    long tiMetaken = endTime - startTime;
    double tiMetakenS = ((double)tiMetaken)/1000000000;



    System.out.println(\"Number of Orders = \" +orderNum);
    System.out.println(\"Number of Trades Generated = \" +TradeNum);
    System.out.println(\"Number of Buy Orders = \" +buyOrderNum);
    System.out.println(\"Number of Sell Orders = \" +sellOrderNum);        
    System.out.println(\"Total Time Taken = \" +tiMetakenS+\" seconds\");

    double orderRate = ((double)(orderNum))/(tiMetakenS);

    System.out.println(\"Order Rate = \" +orderRate+\" per second\");
    double avgTime = (tiMetakenS)/((double)(orderNum))*1000000;
    System.out.println(\"Average Execution Time per Order = \"+avgTime+\" micro seconds\"); 



    //System.out.println(\"Do You Want to Print the Pending Order Books?\");
    //System.out.println(\"y/n?\");

}
}     

解决方法

        如果您在网上遇到
ArrayIndexOutOfBound
例外情况:
buyPriceHeap[0].logid = buyPriceHeap[buyHeapSize-1].logid;
那么显然您需要检查
buyHeapSize
的值。那应该立即向您显示问题所在。 它要么是比数组的实际大小高一些的值,要么为零。在前一种情况下,可能是因为您没有使其与实际阵列保持同步。在后者中,您可能正试图从空堆中删除。 这些是您应该调查的可能原因。这个问题在这里对其他人来说价值是有限的,因此我很担心投入太多时间,而不是说您应该使用调试器来逐步解决问题,或者使用
System.out.println
语句临时添加代码(一般建议而不是特定的解决方案) 。 这两种选择都会使您在调试方面变得更好。