【问题标题】:Whats wrong with my code? It's giving exception [closed]我的代码有什么问题?它给出了例外[关闭]
【发布时间】:2013-05-12 06:30:59
【问题描述】:

我编写了这段代码,因为我想在 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]);
        }
        }
}

【问题讨论】:

  • 为什么不提供它给出的异常?
  • 删除代码中的空行。告诉我们抛出异常的位置。删除所有其他对解释您的问题不必要的代码。
  • 在调试器中单步执行代码时会看到什么。
  • 将数组复制到一个集合(删除重复项),对集合进行排序...并取前 5 个值。

标签: java runtime-error


【解决方案1】:

我猜你会收到ArrayIndexOutOfBoundsException

为了防止这种情况,第 28 行,更改:

index[last]=i;

进入这个:

index[last++]=i;

或更改第 14 行:

int index[]=new int[5];

进入这个:

int index[]=new int[6];

由于您的索引上升到 5(数组大小 - 1)

【讨论】:

    【解决方案2】:

    这个

    last++;
    index[last]=i;
    

    应该改为

    index[last++]=i;
    

    避免ArrayIndexOutOfBoundsException

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 2016-02-27
      • 1970-01-01
      • 2023-03-25
      • 2023-04-11
      • 2013-02-11
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多