-9

7 つの数字のうち 5 つの最小数字を連続して出力したいが、重複した値を出力したくないので、このコードを書きました。今、いくつかの例外を与えています。

これをどうするか?

の動的タイプが必要だと思いますが、Arraylistそれを正確に適用することはできません。

class mycode{

    public static void main(String[] args) {

    boolean lowStraightFound = false;
    int firstCard=0 ;
    int firstCardIndex = 0;
    int lastCard =0;
    int lastCardIndex = 0;
    int c[]={1,2,3,3,4,5,7};
    int[] inarow = new int[20];
    int index[]=new int[5];
    int last=0;

    int num = c.length;
    for (int i = 0; i < num; i++) {
       int card = c[i];
        if (lastCard!= 0) {
            int lastOrd = lastCard;
            int cardOrd = card;
            if (cardOrd - lastOrd  == 1) {
                inarow[0]++;
                lastCardIndex = i;
                last++;
                index[last]=i;   
            } else if (cardOrd - lastOrd != 0) {
                inarow[0] = 1;
                firstCard = card;
                firstCardIndex = i;
                last=0;
                index[last]=i;
               }else if(cardOrd - lastOrd == 0){
                  index[last]=i;
                  last=i;  
               }
        } else {
            firstCard = card;
            firstCardIndex = i;
            index[last]=i;
        }
        lastCard = card;

        if (inarow[0] == 5) {
            lowStraightFound = true;
            break;
        }          
    }
        for (int i = last; i >= 0; i--) {
          System.out.println(c[i]);
        }
        }
}
4

2 に答える 2

1

これ

last++;
index[last]=i;

に変更する必要があります

index[last++]=i;

ArrayIndexOutOfBoundsExceptionを回避します。

于 2013-05-17T06:58:39.067 に答える
0

ArrayIndexOutOfBoundsExceptionが発生すると思います。

これを防ぐには、28 行目を次のように変更します。

index[last]=i;

これに:

index[last++]=i;

または 14 行目を変更します。

int index[]=new int[5];

これに:

int index[]=new int[6];

インデックスは最大 5 (配列サイズ - 1) になるため

于 2013-05-17T06:58:41.750 に答える